From f974e27a3a10e642bd8c9fccdafa013888593277 Mon Sep 17 00:00:00 2001 From: konard Date: Mon, 30 Nov 2026 05:54:14 +0000 Subject: [PATCH 1/6] Initial commit with task details Adding .gitkeep for PR creation (default mode). This file will be removed when the task is complete. Issue: https://github.com/linksplatform/Collections.Methods/issues/114 --- .gitkeep | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitkeep diff --git a/.gitkeep b/.gitkeep new file mode 100644 index 0000000..ef7648a --- /dev/null +++ b/.gitkeep @@ -0,0 +1 @@ +# .gitkeep file auto-generated at 2026-11-30T05:54:14.214Z for PR creation at branch issue-114-680cdc793c86 for issue https://github.com/linksplatform/Collections.Methods/issues/114 \ No newline at end of file From 7b60c3269b3fa36d254724ac8e3624ce60575066 Mon Sep 17 00:00:00 2001 From: konard Date: Mon, 30 Nov 2026 06:06:40 +0000 Subject: [PATCH 2/6] Restore the C# tree and list APIs in NuGet 1.0.1 --- .../scripts/check-csharp-nuget-consumer.sh | 43 ++++++++++++++++ .github/scripts/validate-csharp-package.sh | 3 ++ .github/workflows/csharp.yml | 2 + .gitkeep | 1 - .../Platform.Collections.Methods.csproj | 4 +- .../Trees/SizeBalancedTreeMethods.cs | 6 +-- .../SizedAndThreadedAVLBalancedTreeMethods.cs | 18 +++---- .../Trees/SizedBinaryTreeMethodsBase.cs | 50 +++++++++---------- examples/NuGetConsumer/CollectionMethods.cs | 38 ++++++++++++++ examples/NuGetConsumer/NuGetConsumer.csproj | 9 ++++ 10 files changed, 134 insertions(+), 40 deletions(-) create mode 100755 .github/scripts/check-csharp-nuget-consumer.sh delete mode 100644 .gitkeep create mode 100644 examples/NuGetConsumer/CollectionMethods.cs create mode 100644 examples/NuGetConsumer/NuGetConsumer.csproj diff --git a/.github/scripts/check-csharp-nuget-consumer.sh b/.github/scripts/check-csharp-nuget-consumer.sh new file mode 100755 index 0000000..52ab2a4 --- /dev/null +++ b/.github/scripts/check-csharp-nuget-consumer.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash + +set -euo pipefail + +version="${1:?Usage: check-csharp-nuget-consumer.sh [local package]}" +local_package="${2:-}" +repository_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +cp "$repository_root/examples/NuGetConsumer/"{NuGetConsumer.csproj,CollectionMethods.cs} "$work" +if [[ -n "$local_package" ]]; then + mkdir "$work/feed" + cp "$local_package" "$work/feed/" +fi +cd "$work" + +sources=(--source https://api.nuget.org/v3/index.json) +if [[ -n "$local_package" ]]; then + cat > NuGet.Config <<'XML' + + + + + + + + + + + + + + + +XML + sources=(--configfile NuGet.Config) +fi + +properties=(-p:CollectionsMethodsVersion="$version" -p:TargetFramework="${CONSUMER_FRAMEWORK:-net8.0}") +dotnet restore NuGetConsumer.csproj --nologo --packages "$work/packages" \ + -p:RestoreNoCache=true -p:RestoreNoHttpCache=true "${sources[@]}" "${properties[@]}" +dotnet build NuGetConsumer.csproj --nologo --no-restore --configuration Release "${properties[@]}" diff --git a/.github/scripts/validate-csharp-package.sh b/.github/scripts/validate-csharp-package.sh index d0b76bd..9ad7ecb 100755 --- a/.github/scripts/validate-csharp-package.sh +++ b/.github/scripts/validate-csharp-package.sh @@ -46,4 +46,7 @@ if ! unzip -p "${packages[0]}" README.md | grep -q ''; exit 1 fi +version=$(dotnet msbuild "$package_project" -nologo -getProperty:PackageVersion) +"$repository_root/.github/scripts/check-csharp-nuget-consumer.sh" "$version" "${packages[0]}" + echo "Validated ${packages[0]} with embedded symbols." diff --git a/.github/workflows/csharp.yml b/.github/workflows/csharp.yml index 9cc72e5..4c74f94 100644 --- a/.github/workflows/csharp.yml +++ b/.github/workflows/csharp.yml @@ -5,6 +5,7 @@ on: branches: main paths: - 'csharp/**' + - 'examples/NuGetConsumer/**' - 'README.md' - '.github/scripts/*csharp*' - '.github/scripts/*nuget-*' @@ -13,6 +14,7 @@ on: branches: main paths: - 'csharp/**' + - 'examples/NuGetConsumer/**' - 'README.md' - '.github/scripts/*csharp*' - '.github/scripts/*nuget-*' diff --git a/.gitkeep b/.gitkeep deleted file mode 100644 index ef7648a..0000000 --- a/.gitkeep +++ /dev/null @@ -1 +0,0 @@ -# .gitkeep file auto-generated at 2026-11-30T05:54:14.214Z for PR creation at branch issue-114-680cdc793c86 for issue https://github.com/linksplatform/Collections.Methods/issues/114 \ No newline at end of file diff --git a/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj b/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj index 3d85b34..19636ad 100644 --- a/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj +++ b/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj @@ -4,7 +4,7 @@ LinksPlatform's Platform.Collections.Methods Class Library: methods of size balanced, recursionless size balanced and AVL trees and of four doubly linked lists over storage you provide. README.md compares them by speed, memory and limits, with C# and C++ benchmark results. Konstantin Diachenko Platform.Collections.Methods - 0.8.0 + 1.0.1 Konstantin Diachenko net8 Platform.Collections.Methods @@ -23,7 +23,7 @@ true embedded latest - Size balanced trees keep Chen's size balanced property on every attach and detach, so their height never exceeds the AVL bound; the recursionless variant now builds the same trees as the recursive one; trees built by older versions are rebuilt once in linear time. + Restores the Platform.Collections.Methods.Trees and Platform.Collections.Methods.Lists APIs after the legacy 1.0.0 package. Targets .NET 8 and later. Size balanced trees keep Chen's size balanced property on every attach and detach, so their height never exceeds the AVL bound. The recursionless variant builds the same trees as the recursive one. Trees built by older versions are rebuilt once in linear time. enable diff --git a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs index 87f3d34..77a5f08 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs @@ -92,7 +92,7 @@ private int AttachCounting(ref TElement root, TElement node) /// The reference to the root of the subtree. /// Ссылка на корень поддерева. /// - /// + /// /// The node to detach. /// Отсоединяемый узел. /// @@ -100,10 +100,10 @@ private int AttachCounting(ref TElement root, TElement node) /// The node is not in the tree, or another node has the same key. /// Узла нет в дереве, или другой узел имеет такой же ключ. /// - protected override void DetachCore(ref TElement root, TElement node) + protected override void DetachCore(ref TElement root, TElement nodeToDetach) { var size = GetSizeOrZero(root); - if (DetachCounting(ref root, node) > GetMaximumBalancedHeight(size)) + if (DetachCounting(ref root, nodeToDetach) > GetMaximumBalancedHeight(size)) { // The path was longer than in any size balanced tree, so the tree was built by other code. root = RebuildComplete(root); diff --git a/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs index 9edd5ba..9d7682b 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs @@ -126,22 +126,22 @@ public override bool Contains(TElement node, TElement root) /// The node. /// /// - /// - /// The stringBuilder. + /// + /// The string builder. /// /// /// /// The level. /// /// - protected override void PrintNode(TElement node, StringBuilder stringBuilder, int level) + protected override void PrintNode(TElement node, StringBuilder sb, int level) { - base.PrintNode(node, stringBuilder, level); - stringBuilder.Append(' '); - stringBuilder.Append(GetLeftIsChild(node) ? 'l' : 'L'); - stringBuilder.Append(GetRightIsChild(node) ? 'r' : 'R'); - stringBuilder.Append(' '); - stringBuilder.Append(GetBalance(node)); + base.PrintNode(node, sb, level); + sb.Append(' '); + sb.Append(GetLeftIsChild(node) ? 'l' : 'L'); + sb.Append(GetRightIsChild(node) ? 'r' : 'R'); + sb.Append(' '); + sb.Append(GetBalance(node)); } /// diff --git a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs index c32b516..a148710 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs @@ -899,12 +899,12 @@ public string PrintNodes(TElement node) /// The node. /// /// - /// - /// The stringBuilder. + /// + /// The string builder. /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void PrintNodes(TElement node, StringBuilder stringBuilder) => PrintNodes(node, stringBuilder, 0); + public void PrintNodes(TElement node, StringBuilder sb) => PrintNodes(node, sb, 0); /// /// @@ -916,24 +916,24 @@ public string PrintNodes(TElement node) /// The node. /// /// - /// - /// The stringBuilder. + /// + /// The string builder. /// /// /// /// The level. /// /// - public void PrintNodes(TElement node, StringBuilder stringBuilder, int level) + public void PrintNodes(TElement node, StringBuilder sb, int level) { if (node == default) { return; } - PrintNodes(GetLeftOrDefault(node), stringBuilder, level + 1); - PrintNode(node, stringBuilder, level); - stringBuilder.AppendLine(); - PrintNodes(GetRightOrDefault(node), stringBuilder, level + 1); + PrintNodes(GetLeftOrDefault(node), sb, level + 1); + PrintNode(node, sb, level); + sb.AppendLine(); + PrintNodes(GetRightOrDefault(node), sb, level + 1); } /// @@ -967,12 +967,12 @@ public string PrintNode(TElement node) /// The node. /// /// - /// - /// The stringBuilder. + /// + /// The string builder. /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void PrintNode(TElement node, StringBuilder stringBuilder) => PrintNode(node, stringBuilder, 0); + protected void PrintNode(TElement node, StringBuilder sb) => PrintNode(node, sb, 0); /// /// @@ -984,22 +984,22 @@ public string PrintNode(TElement node) /// The node. /// /// - /// - /// The stringBuilder. + /// + /// The string builder. /// /// /// /// The level. /// /// - protected virtual void PrintNode(TElement node, StringBuilder stringBuilder, int level) + protected virtual void PrintNode(TElement node, StringBuilder sb, int level) { - stringBuilder.Append('\t', level); - stringBuilder.Append(node); - PrintNodeValue(node, stringBuilder); - stringBuilder.Append(' '); - stringBuilder.Append('s'); - stringBuilder.Append(GetSize(node)); + sb.Append('\t', level); + sb.Append(node); + PrintNodeValue(node, sb); + sb.Append(' '); + sb.Append('s'); + sb.Append(GetSize(node)); } /// @@ -1012,10 +1012,10 @@ protected virtual void PrintNode(TElement node, StringBuilder stringBuilder, int /// The node. /// /// - /// - /// The stringBuilder. + /// + /// The string builder. /// /// - protected abstract void PrintNodeValue(TElement node, StringBuilder stringBuilder); + protected abstract void PrintNodeValue(TElement node, StringBuilder sb); } } diff --git a/examples/NuGetConsumer/CollectionMethods.cs b/examples/NuGetConsumer/CollectionMethods.cs new file mode 100644 index 0000000..68b3ef4 --- /dev/null +++ b/examples/NuGetConsumer/CollectionMethods.cs @@ -0,0 +1,38 @@ +using System.Text; +using Platform.Collections.Methods.Lists; +using Platform.Collections.Methods.Trees; + +public static class CollectionMethods +{ + public static void MoveNode( + SizedAndThreadedAVLBalancedTreeMethods source, + ref uint sourceRoot, + RecursionlessSizeBalancedTreeMethods destination, + ref uint destinationRoot, + uint node) + { + source.Detach(ref sourceRoot, node); + destination.Attach(ref destinationRoot, node); + } + + public static string FormatTree(SizedBinaryTreeMethodsBase tree, uint root) + { + var output = new StringBuilder(); + tree.PrintNodes(node: root, sb: output); + return output.ToString(); + } + + public static void AppendToLists( + AbsoluteCircularDoublyLinkedListMethods absoluteCircular, + AbsoluteOpenDoublyLinkedListMethods absoluteOpen, + RelativeCircularDoublyLinkedListMethods relativeCircular, + RelativeOpenDoublyLinkedListMethods relativeOpen, + uint list, + uint node) + { + absoluteCircular.AttachAsLast(node); + absoluteOpen.AttachAsLast(node); + relativeCircular.AttachAsLast(list, node); + relativeOpen.AttachAsLast(list, node); + } +} diff --git a/examples/NuGetConsumer/NuGetConsumer.csproj b/examples/NuGetConsumer/NuGetConsumer.csproj new file mode 100644 index 0000000..f088f11 --- /dev/null +++ b/examples/NuGetConsumer/NuGetConsumer.csproj @@ -0,0 +1,9 @@ + + + net8.0 + 1.0.1 + + + + + From c90b5a72c60f8c997b077dd97ead167d00fc8dcf Mon Sep 17 00:00:00 2001 From: konard Date: Mon, 30 Nov 2026 06:06:40 +0000 Subject: [PATCH 3/6] Preflight trusted NuGet publishing and fall back on auth failure --- .github/scripts/cpp-workflow-policy.test.mjs | 9 +- .../scripts/csharp-workflow-policy.test.mjs | 12 +- .github/scripts/preflight-nuget-release.mjs | 187 +++++++++++------- .../scripts/preflight-nuget-release.test.mjs | 96 +++++++-- .github/scripts/push-nuget-package.sh | 62 +++--- .github/scripts/push-nuget-package.test.mjs | 51 ++++- .github/workflows/csharp.yml | 43 +++- .github/workflows/deploy-cpp.yml | 41 +++- README.md | 31 ++- 9 files changed, 392 insertions(+), 140 deletions(-) diff --git a/.github/scripts/cpp-workflow-policy.test.mjs b/.github/scripts/cpp-workflow-policy.test.mjs index 98a398a..2f11304 100644 --- a/.github/scripts/cpp-workflow-policy.test.mjs +++ b/.github/scripts/cpp-workflow-policy.test.mjs @@ -79,7 +79,9 @@ test("packs with dotnet and verifies the package on every run", () => { 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("releasePreflight"), /preflight-nuget-release\.mjs check-version/); + assert.match(deployJobs.get("releasePreflight"), /github\.ref == 'refs\/heads\/main'/); + assert.match(deployJobs.get("releasePreflight"), /continue-on-error: true\n +uses: NuGet\/login@/); assert.match(deployJobs.get("pushToNuget"), /needs: \[test, releasePreflight\]/); assert.match(deployJobs.get("pushToNuget"), /push-nuget-package\.sh "\$RUNNER_TEMP\/cpp-nuget"\/\*\.nupkg/); }); @@ -88,7 +90,10 @@ 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 \}\}/); + assert.match(job, /NUGET_OIDC_KEY: .*steps\.nuget-login\.outputs\.NUGET_API_KEY/); + assert.match(job, /NUGET_TOKEN: \$\{\{ secrets\.NUGET_TOKEN \}\}/); + assert.match(job, /continue-on-error: true\n +uses: NuGet\/login@/); + assert.match(job, /wait-for-package/); }); test("creates the GitHub release only after the NuGet push succeeded", () => { diff --git a/.github/scripts/csharp-workflow-policy.test.mjs b/.github/scripts/csharp-workflow-policy.test.mjs index 3434361..28362e0 100644 --- a/.github/scripts/csharp-workflow-policy.test.mjs +++ b/.github/scripts/csharp-workflow-policy.test.mjs @@ -69,7 +69,9 @@ test("gates both package publishers on a release preflight", () => { 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/); + assert.match(preflight, /preflight-nuget-release\.mjs check-version/); + assert.match(preflight, /github\.event_name == 'push'/); + assert.match(preflight, /continue-on-error: true\n +uses: NuGet\/login@/); for (const name of [ "pushNuGetPackageToGitHubPackageRegistry", @@ -120,10 +122,14 @@ test("publishes to nuget.org only when the preflight found the version missing", 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' \}\}/, + /if: \$\{\{ needs\.releasePreflight\.outputs\.publishRequired == 'true' && vars\.NUGET_USER != '' \}\}/, ); 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.match(job, /NUGET_OIDC_KEY: .*steps\.nuget-login\.outputs\.NUGET_API_KEY/); + assert.match(job, /NUGET_TOKEN: \$\{\{ secrets\.NUGET_TOKEN \}\}/); + assert.match(job, /continue-on-error: true\n +uses: NuGet\/login@/); + assert.match(job, /wait-for-package/); + assert.match(job, /check-csharp-nuget-consumer\.sh/); assert.doesNotMatch(job, /run: dotnet nuget push/); }); diff --git a/.github/scripts/preflight-nuget-release.mjs b/.github/scripts/preflight-nuget-release.mjs index 3b7e60f..b8dc3c6 100644 --- a/.github/scripts/preflight-nuget-release.mjs +++ b/.github/scripts/preflight-nuget-release.mjs @@ -11,25 +11,25 @@ * 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. + * GET /api/v2/verifykey// with the original key checks + * the push scope for an existing package. The verification key returned by + * the symbol-package endpoint does not retain the original package glob. * * 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. + * GITHUB_TOKEN, NUGET_TOKEN, NUGET_USER, NUGET_OIDC_KEY, NUGET_INDEX_URL and + * NUGET_GALLERY_URL and NUGET_REGISTRATION_URL (tests), VERBOSE=1 or + * RUNNER_DEBUG=1 for diagnostic output. + * Run check-version before requesting credentials, and wait-for-package after + * publishing to verify public availability and listing without credentials. */ import { appendFileSync, readFileSync } from "node:fs"; +import { setTimeout as delay } from "node:timers/promises"; const defaultIndexUrl = "https://api.nuget.org/v3-flatcontainer"; const defaultGalleryUrl = "https://www.nuget.org"; +const defaultRegistrationUrl = "https://api.nuget.org/v3/registration5-gz-semver2"; +const registryRequest = () => ({ cache: "no-store", signal: AbortSignal.timeout(10_000) }); export const readCsproj = (source) => { const read = (name) => new RegExp(`<${name}>([^<]+)`).exec(source)?.[1]?.trim(); @@ -50,14 +50,17 @@ export const versionIndexUrl = (packageId, indexUrl = defaultIndexUrl) => 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) }); + const response = await fetchImpl(url, registryRequest()); 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(); + const { versions } = await response.json(); + if (!Array.isArray(versions) || !versions.every((entry) => typeof entry === "string")) { + return { published: undefined, detail: `${url} returned an invalid version list` }; + } return { published: versions.includes(version.toLowerCase()), latest: versions.at(-1), @@ -68,6 +71,18 @@ export const fetchPublished = async ({ packageId, version, indexUrl, fetchImpl = } }; +const checkListing = async ({ packageId, version, registrationUrl, fetchImpl }) => { + const url = `${registrationUrl}/${packageId.toLowerCase()}/${version.toLowerCase()}.json`; + try { + const response = await fetchImpl(url, registryRequest()); + if (!response.ok) return `${url} returned ${response.status}`; + if ((await response.json()).listed === true) return undefined; + return `${url} did not report a listed package`; + } catch (error) { + return `${url} failed: ${error.message}`; + } +}; + /** * @returns {Promise<{ valid: boolean | undefined, detail: string }>} * `valid` is undefined when nuget.org could not answer, and also when no @@ -82,54 +97,37 @@ export const verifyApiKey = async ({ fetchImpl = fetch, }) => { const id = encodeURIComponent(packageId); - const createUrl = `${galleryUrl}/api/v2/package/create-verification-key/${id}`; - let key; + const url = publishedVersion + ? `${galleryUrl}/api/v2/verifykey/${id}/${encodeURIComponent(publishedVersion)}` + : `${galleryUrl}/api/v2/package/create-verification-key/${id}`; try { - const response = await fetchImpl(createUrl, { - method: "POST", + const response = await fetchImpl(url, { + method: publishedVersion ? "GET" : "POST", headers: { "X-NuGet-ApiKey": apiKey }, - body: "", + body: publishedVersion ? undefined : "", + redirect: "error", signal: AbortSignal.timeout(30_000), }); if (response.status === 401 || response.status === 403) { - return { valid: false, detail: `${createUrl} returned ${response.status}` }; + return { valid: false, detail: `${url} returned ${response.status}` }; } if (!response.ok) { - return { valid: undefined, detail: `${createUrl} returned ${response.status}` }; + return { valid: undefined, detail: `${url} 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}` }; + if (!publishedVersion) { + const { Key: verificationKey } = await response.json(); + const detail = verificationKey + ? `${url} accepted the key, but no published version is available to check its package scope` + : `${url} returned no verification key`; + return { valid: undefined, detail }; } - return { - valid: response.ok ? true : undefined, - detail: `${verifyUrl} returned ${response.status}`, - }; + return { valid: true, detail: `${url} returned ${response.status}` }; } catch (error) { - return { valid: undefined, detail: `${verifyUrl} failed: ${error.message}` }; + return { valid: undefined, detail: `${url} failed: ${error.message}` }; } }; -export const evaluateRelease = ({ published, githubToken, nugetToken, nugetUser, keyValid, keyDetail }) => { +export const evaluateRelease = ({ published, githubToken, nugetToken, trustedAvailable, keyValid, keyDetail }) => { const failures = []; const warnings = []; @@ -138,21 +136,21 @@ export const evaluateRelease = ({ published, githubToken, nugetToken, nugetUser, } if (published === undefined) { warnings.push( - "nuget.org could not be queried; the push will run with --skip-duplicate", + "nuget.org could not be queried. If credentials are available, the push will use --skip-duplicate", ); } const publishRequired = published !== true; let auth = "none"; - if (nugetUser) { + if (publishRequired && trustedAvailable) { auth = "trusted-publishing"; - } else if (nugetToken) { + } else if (publishRequired && 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", + "No NuGet publishing credential is available. Configure the nuget.org trusted publishing policy and set NUGET_USER to its creator's username, or configure the NUGET_TOKEN secret with push scope for this package", ); } if (publishRequired && auth === "api-key") { @@ -176,8 +174,7 @@ const setOutput = (environment, name, value) => { } }; -export const run = async (environment = process.env, fetchImpl = fetch) => { - const verbose = environment.VERBOSE === "1" || environment.RUNNER_DEBUG === "1"; +const readPackage = (environment) => { let packageId = environment.PACKAGE_ID; let version = environment.PACKAGE_VERSION; if (environment.CSPROJ) { @@ -185,33 +182,80 @@ export const run = async (environment = process.env, fetchImpl = fetch) => { packageId ||= project.packageId; version ||= project.version; } + return { packageId, version }; +}; + +export const run = async (environment = process.env, fetchImpl = fetch, command, wait = delay) => { + const verbose = environment.VERBOSE === "1" || environment.RUNNER_DEBUG === "1"; + const { packageId, version } = readPackage(environment); 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({ + const query = () => fetchPublished({ packageId, version, indexUrl: environment.NUGET_INDEX_URL || defaultIndexUrl, fetchImpl, }); - if (verbose) { + if (command === "wait-for-package") { + const registrationUrl = environment.NUGET_REGISTRATION_URL || defaultRegistrationUrl; + for (let attempt = 0; attempt <= 30; attempt += 1) { + const { published, detail } = await query(); + if (published) { + const listingProblem = await checkListing({ packageId, version, registrationUrl, fetchImpl }); + if (!listingProblem) { + console.log(`${packageId} ${version} is listed and available anonymously from nuget.org.`); + return 0; + } + if (verbose) console.log(`Registration: ${listingProblem}`); + } + if (verbose) console.log(`Version index: ${detail}`); + if (attempt < 30) await wait(30_000); + } + console.error(`::error title=NuGet indexing failed::${packageId} ${version} was not verified as available and listed on nuget.org. Check its listing and rerun the failed job.`); + return 1; + } + + const { published, latest, detail } = environment.PUBLISHED_STATE && command !== "check-version" + ? { published: { true: true, false: false }[environment.PUBLISHED_STATE], latest: environment.PUBLISHED_VERSION } + : await query(); + if (verbose && detail) { console.log(`Version index: ${detail}`); } + if (command === "check-version") { + setOutput(environment, "published_state", published === undefined ? "unknown" : String(published)); + setOutput(environment, "published_version", latest ?? ""); + return 0; + } const nugetToken = environment.NUGET_TOKEN ?? ""; - const nugetUser = environment.NUGET_USER ?? ""; + const verify = (apiKey) => verifyApiKey({ + packageId, + publishedVersion: latest, + apiKey, + galleryUrl: environment.NUGET_GALLERY_URL || defaultGalleryUrl, + fetchImpl, + }); + let trustedAvailable = false; + if (published !== true && environment.NUGET_USER) { + if (environment.NUGET_OIDC_KEY) { + const verification = await verify(environment.NUGET_OIDC_KEY); + trustedAvailable = verification.valid !== false; + if (verification.valid === undefined) { + console.log(`::warning title=NuGet release preflight::Trusted publishing exchanged an OIDC token, but package push scope is unverified (${verification.detail})`); + } else if (verification.valid === false) { + console.log(`::warning title=NuGet release preflight::NuGet rejected the trusted publishing key (${verification.detail}). Check the policy's package owner and push scope.`); + } + } else { + console.log("::warning title=NuGet release preflight::Trusted publishing login did not return a key. Check the policy's repository and workflow file and set NUGET_USER to the policy creator's username."); + } + } 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, - }); + if (published !== true && nugetToken && !trustedAvailable) { + const verification = await verify(nugetToken); keyValid = verification.valid; keyDetail = verification.detail; if (verbose) { @@ -223,7 +267,7 @@ export const run = async (environment = process.env, fetchImpl = fetch) => { published, githubToken: environment.GITHUB_TOKEN ?? "", nugetToken, - nugetUser, + trustedAvailable, keyValid, keyDetail, }); @@ -235,13 +279,10 @@ export const run = async (environment = process.env, fetchImpl = fetch) => { 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 { + if (!result.publishRequired) { console.log(`${packageId} ${version} is already on nuget.org; publishing will be skipped.`); + } else if (result.passed) { + console.log(`Publishing ${packageId} ${version} has an available credential: ${result.auth}.`); } setOutput(environment, "publish_required", String(result.publishRequired)); @@ -250,5 +291,5 @@ export const run = async (environment = process.env, fetchImpl = fetch) => { }; if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { - process.exitCode = await run(); + process.exitCode = await run(process.env, fetch, process.argv[2]); } diff --git a/.github/scripts/preflight-nuget-release.test.mjs b/.github/scripts/preflight-nuget-release.test.mjs index 792e95e..3e2b3bd 100644 --- a/.github/scripts/preflight-nuget-release.test.mjs +++ b/.github/scripts/preflight-nuget-release.test.mjs @@ -44,6 +44,7 @@ test("detects published, unpublished, unknown and unreachable packages", async ( 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(respond(200, { versions: "invalid" }))).published, undefined); assert.equal( (await query(async () => { throw new Error("offline"); @@ -68,7 +69,7 @@ test("fails before pushing when an unpublished version has no credentials", () = }); test("prefers trusted publishing over the long-lived API key", () => { - const result = evaluateRelease({ published: false, githubToken: "g", nugetToken: "k", nugetUser: "linksplatform" }); + const result = evaluateRelease({ published: false, githubToken: "g", nugetToken: "k", trustedAvailable: true }); assert.equal(result.auth, "trusted-publishing"); assert.equal(result.passed, true); }); @@ -112,9 +113,8 @@ const gallery = (routes) => { 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 () => { +test("verifies the original key and its package glob without publishing", async () => { const { calls, fetchImpl } = gallery({ - [createUrl]: [200, { Key: "one-time", Expires: "2026-10-07T00:00:00Z" }], [verifyUrl]: [200], }); const result = await verifyApiKey({ @@ -125,14 +125,13 @@ test("verifies an API key in two steps without publishing", async () => { }); assert.equal(result.valid, true); assert.deepEqual(calls, [ - { request: createUrl, key: "secret" }, - { request: verifyUrl, key: "one-time" }, + { request: verifyUrl, key: "secret" }, ]); }); 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 { calls, fetchImpl } = gallery({ [verifyUrl]: [status] }); const result = await verifyApiKey({ packageId: "Platform.Collections.Methods", publishedVersion: "0.5.0", @@ -146,7 +145,6 @@ test("rejects an invalid or expired API key (linksplatform/Interfaces#150)", asy 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({ @@ -169,8 +167,7 @@ test("does not claim a package scope it cannot check for a package that was neve 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({ [verifyUrl]: [503] }).fetchImpl)).valid, undefined); assert.equal( (await verify(gallery({ [createUrl]: [200, { Key: "one-time" }], [verifyUrl]: [500] }).fetchImpl)).valid, undefined, @@ -205,7 +202,7 @@ test("does not verify NUGET_TOKEN when nothing has to be published", async () => 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], + [verifyUrl]: [403], }); const exitCode = await run( { PACKAGE_ID: "Platform.Collections.Methods", PACKAGE_VERSION: "0.6.1", GITHUB_TOKEN: "g", NUGET_TOKEN: "expired" }, @@ -218,7 +215,6 @@ test("fails the preflight with an expired NUGET_TOKEN for an unpublished version 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( @@ -248,3 +244,81 @@ test("writes the decision to GITHUB_OUTPUT", async () => { rmSync(directory, { recursive: true, force: true }); } }); + +const pendingRelease = { + PACKAGE_ID: "Platform.Collections.Methods", + PACKAGE_VERSION: "0.6.1", + PUBLISHED_STATE: "false", + PUBLISHED_VERSION: "0.5.0", + GITHUB_TOKEN: "g", + NUGET_USER: "policy-creator", +}; + +test("preflights the short-lived key without using the fallback", async () => { + const { calls, fetchImpl } = gallery({ [verifyUrl]: [200] }); + assert.equal(await run({ ...pendingRelease, NUGET_OIDC_KEY: "oidc", NUGET_TOKEN: "fallback" }, fetchImpl), 0); + assert.deepEqual(calls, [{ request: verifyUrl, key: "oidc" }]); +}); + +test("preflights the fallback when exchange fails or the short-lived key is denied", async () => { + for (const oidcKey of ["", "oidc"]) { + const keys = []; + const fetchImpl = async (_url, options) => { + const key = options.headers["X-NuGet-ApiKey"]; + keys.push(key); + return respond(key === "oidc" ? 403 : 200)(); + }; + assert.equal(await run({ ...pendingRelease, NUGET_OIDC_KEY: oidcKey, NUGET_TOKEN: "fallback" }, fetchImpl), 0); + assert.deepEqual(keys, oidcKey ? ["oidc", "fallback"] : ["fallback"]); + } +}); + +test("fails preflight when a configured trusted publisher does not return a key and fallback is missing", async () => { + const { calls, fetchImpl } = gallery({}); + assert.equal(await run(pendingRelease, fetchImpl), 1); + assert.deepEqual(calls, []); +}); + +test("makes the version check available to the workflow before any credentials are used", async () => { + const directory = mkdtempSync(path.join(tmpdir(), "preflight-")); + const output = path.join(directory, "output"); + try { + const { calls, fetchImpl } = gallery({ + "GET https://api.nuget.org/v3-flatcontainer/platform.collections.methods/index.json": [200, { versions: ["0.5.0"] }], + }); + assert.equal(await run({ ...pendingRelease, GITHUB_OUTPUT: output }, fetchImpl, "check-version"), 0); + assert.equal(readFileSync(output, "utf8"), "published_state=false\npublished_version=0.5.0\n"); + assert.equal(calls.length, 1); + assert.equal(calls[0].key, undefined); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("waits for an anonymously downloadable and listed package", async () => { + const keylessRequests = []; + let indexRequests = 0; + let registrationRequests = 0; + let waits = 0; + const fetchImpl = async (url, options) => { + keylessRequests.push(options.headers); + if (url.includes("/v3-flatcontainer/")) { + indexRequests += 1; + return respond(200, { versions: indexRequests === 1 ? ["0.5.0"] : ["0.5.0", "0.6.1"] })(); + } + assert.match(url, /\/registration5-gz-semver2\/platform\.collections\.methods\/0\.6\.1\.json$/); + registrationRequests += 1; + return respond(200, { listed: registrationRequests > 1 })(); + }; + assert.equal(await run(pendingRelease, fetchImpl, "wait-for-package", async () => { waits += 1; }), 0); + assert.equal(waits, 2); + assert.equal(indexRequests, 3); + assert.equal(registrationRequests, 2); + assert.ok(keylessRequests.every((headers) => headers === undefined)); +}); + +test("fails when the public registry still has no listed package after the polling budget", async () => { + let waits = 0; + assert.equal(await run(pendingRelease, respond(404), "wait-for-package", async () => { waits += 1; }), 1); + assert.equal(waits, 30); +}); diff --git a/.github/scripts/push-nuget-package.sh b/.github/scripts/push-nuget-package.sh index 91e1786..535ab43 100755 --- a/.github/scripts/push-nuget-package.sh +++ b/.github/scripts/push-nuget-package.sh @@ -6,16 +6,12 @@ # # Usage: push-nuget-package.sh # Environment: -# NUGET_API_KEY short-lived trusted-publishing key or the NUGET_TOKEN secret +# NUGET_OIDC_KEY short-lived key from NuGet/login (preferred) +# NUGET_TOKEN legacy API key, used only for an authentication fallback +# NUGET_USER username configured for trusted publishing, when set # 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." @@ -25,25 +21,47 @@ 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 + +push_package() { + DOTNET_CLI_UI_LANGUAGE=en-US dotnet nuget push "$package" \ + --source https://api.nuget.org/v3/index.json \ + --api-key "$1" \ + --skip-duplicate 2>&1 | tee "$log" +} + +auth_rejected() { + grep -qiE 'Response status code does not indicate success: (401|403)([^[:digit:]]|$)' "$log" +} + +if [ -n "${NUGET_OIDC_KEY:-}" ]; then + if push_package "$NUGET_OIDC_KEY"; then + exit 0 + fi + if ! auth_rejected; then + exit 1 + fi + workflow_ref=${GITHUB_WORKFLOW_REF:-the release workflow} + policy_hint="Check the trusted publishing policy's package owner and push scope for ${workflow_ref%@*}." + if [ -z "${NUGET_TOKEN:-}" ]; then + echo "::error title=nuget.org rejected the trusted publishing key::$policy_hint Configure NUGET_TOKEN if API-key fallback is needed." + exit 1 + fi + echo "::warning title=NuGet authentication fallback::The trusted publishing key was rejected. Trying NUGET_TOKEN. $policy_hint" +elif [ -n "${NUGET_USER:-}" ] && [ -n "${NUGET_TOKEN:-}" ]; then + echo "::warning title=NuGet authentication fallback::Trusted publishing login did not return a key. Trying NUGET_TOKEN." +fi + +if [ -z "${NUGET_TOKEN:-}" ]; then + echo "::error title=NuGet push failed::No API key. Configure the nuget.org trusted publishing policy and set NUGET_USER to its creator's username, or configure NUGET_TOKEN with push scope for this package." + exit 1 +fi +if push_package "$NUGET_TOKEN"; 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 +if auth_rejected; then + echo "::error title=nuget.org rejected NUGET_TOKEN::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 NUGET_USER to the policy creator's username." fi exit 1 diff --git a/.github/scripts/push-nuget-package.test.mjs b/.github/scripts/push-nuget-package.test.mjs index cab896b..f51fd14 100644 --- a/.github/scripts/push-nuget-package.test.mjs +++ b/.github/scripts/push-nuget-package.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; @@ -16,7 +16,7 @@ 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`); + 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"); @@ -50,7 +50,7 @@ test("fails without a key instead of silently skipping", () => { test("pushes with --skip-duplicate to nuget.org", () => { withFakeDotnet("exit 0", ({ directory, nupkg }) => { - const result = push(directory, nupkg, { NUGET_API_KEY: "key" }); + const result = push(directory, nupkg, { NUGET_TOKEN: "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/); @@ -59,7 +59,7 @@ test("pushes with --skip-duplicate to nuget.org", () => { 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" }); + const result = push(directory, nupkg, { NUGET_TOKEN: "expired" }); assert.equal(result.status, 1); assert.match(result.stdout, /::error title=nuget\.org rejected NUGET_TOKEN::/); assert.match(result.stdout, /trusted-publishing/); @@ -69,20 +69,55 @@ test("explains how to renew an expired NUGET_TOKEN", () => { 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", + NUGET_OIDC_KEY: "short-lived", 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/); + 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" }); + const result = push(directory, nupkg, { NUGET_TOKEN: "key" }); assert.equal(result.status, 1); assert.doesNotMatch(result.stdout, /rejected/); }); }); + +const pushWithEitherKey = (dotnetBody, environment, expectedKeys, expectedStatus = 0) => { + withFakeDotnet(dotnetBody, ({ directory, nupkg }) => { + const result = push(directory, nupkg, environment); + assert.equal(result.status, expectedStatus, result.stdout); + const calls = readFileSync(path.join(directory, "args"), "utf8").trim().split("\n"); + assert.deepEqual(calls.map((line) => /--api-key (\S+)/.exec(line)[1]), expectedKeys); + for (const key of expectedKeys) { + assert.ok(!result.stdout.includes(key) && !result.stderr.includes(key)); + } + }); +}; + +test("uses the short-lived key first without printing it even in debug mode", () => { + pushWithEitherKey("exit 0", { + NUGET_OIDC_KEY: "short-lived", + NUGET_TOKEN: "fallback-secret", + RUNNER_DEBUG: "1", + }, ["short-lived"]); +}); + +test("pushes with the fallback if OIDC login returned no key", () => { + pushWithEitherKey("exit 0", { NUGET_USER: "configured", NUGET_TOKEN: "fallback-secret" }, ["fallback-secret"]); +}); + +test("retries with the fallback only when the trusted key is denied", () => { + const dotnet = `if [[ "$*" == *short-lived* ]]; then echo '${rejectedKey}'; exit 1; fi`; + pushWithEitherKey(dotnet, { NUGET_OIDC_KEY: "short-lived", NUGET_TOKEN: "fallback-secret" }, ["short-lived", "fallback-secret"]); +}); + +test("does not use the fallback after a non-authentication error", () => { + pushWithEitherKey("echo 'error: 500 (Internal Server Error)'; exit 1", { + NUGET_OIDC_KEY: "short-lived", + NUGET_TOKEN: "fallback-secret", + }, ["short-lived"], 1); +}); diff --git a/.github/workflows/csharp.yml b/.github/workflows/csharp.yml index 4c74f94..09f29d2 100644 --- a/.github/workflows/csharp.yml +++ b/.github/workflows/csharp.yml @@ -113,18 +113,37 @@ jobs: if: ${{ github.event_name == 'push' }} runs-on: ubuntu-24.04 timeout-minutes: 5 + permissions: + contents: read + id-token: write 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 + - name: Check public package version + id: version + env: + CSPROJ: Platform.Collections.Methods/Platform.Collections.Methods.csproj + run: node ../.github/scripts/preflight-nuget-release.mjs check-version + + - name: Log in to NuGet for release preflight + id: nuget-login + if: ${{ steps.version.outputs.published_state != 'true' && vars.NUGET_USER != '' }} + continue-on-error: true + uses: NuGet/login@8d196754b4036150537f80ac539e15c2f1028841 # v1.2.0 + with: + user: ${{ vars.NUGET_USER }} + + - name: Check release credentials id: preflight env: CSPROJ: Platform.Collections.Methods/Platform.Collections.Methods.csproj + PUBLISHED_STATE: ${{ steps.version.outputs.published_state }} + PUBLISHED_VERSION: ${{ steps.version.outputs.published_version }} + NUGET_OIDC_KEY: ${{ steps.nuget-login.outcome == 'success' && steps.nuget-login.outputs.NUGET_API_KEY || '' }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} NUGET_USER: ${{ vars.NUGET_USER }} @@ -167,7 +186,7 @@ jobs: needs: [test, coverage, treeValidation, releasePreflight] if: ${{ github.event_name == 'push' }} runs-on: ubuntu-24.04 - timeout-minutes: 10 + timeout-minutes: 30 permissions: contents: read id-token: write @@ -186,18 +205,30 @@ jobs: - name: Log in to NuGet with trusted publishing id: nuget-login - if: ${{ needs.releasePreflight.outputs.auth == 'trusted-publishing' && needs.releasePreflight.outputs.publishRequired == 'true' }} + if: ${{ needs.releasePreflight.outputs.publishRequired == 'true' && vars.NUGET_USER != '' }} + continue-on-error: 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 }} + NUGET_USER: ${{ vars.NUGET_USER }} PUBLISH_REQUIRED: ${{ needs.releasePreflight.outputs.publishRequired }} - NUGET_API_KEY: ${{ steps.nuget-login.outputs.NUGET_API_KEY || secrets.NUGET_TOKEN }} + NUGET_OIDC_KEY: ${{ steps.nuget-login.outcome == 'success' && steps.nuget-login.outputs.NUGET_API_KEY || '' }} + NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} run: ../.github/scripts/push-nuget-package.sh "$RUNNER_TEMP/nuget-packages"/*.nupkg + - name: Verify the public NuGet package + env: + CSPROJ: Platform.Collections.Methods/Platform.Collections.Methods.csproj + run: node ../.github/scripts/preflight-nuget-release.mjs wait-for-package + + - name: Build a consumer of the public NuGet package + run: | + version=$(dotnet msbuild Platform.Collections.Methods/Platform.Collections.Methods.csproj -nologo -getProperty:PackageVersion) + ../.github/scripts/check-csharp-nuget-consumer.sh "$version" + publishRelease: needs: [pushNuGetPackageToGitHubPackageRegistry, pushToNuget] if: ${{ github.event_name == 'push' }} diff --git a/.github/workflows/deploy-cpp.yml b/.github/workflows/deploy-cpp.yml index 586aab9..c60ccb5 100644 --- a/.github/workflows/deploy-cpp.yml +++ b/.github/workflows/deploy-cpp.yml @@ -31,21 +31,42 @@ jobs: releasePreflight: needs: test + if: ${{ github.ref == 'refs/heads/main' }} runs-on: ubuntu-24.04 timeout-minutes: 5 + permissions: + contents: read + id-token: write 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 + - name: Check public package version + id: version + env: + PACKAGE_ID: ${{ needs.test.outputs.package_id }} + PACKAGE_VERSION: ${{ needs.test.outputs.version }} + run: node .github/scripts/preflight-nuget-release.mjs check-version + + - name: Log in to NuGet for release preflight + id: nuget-login + if: ${{ steps.version.outputs.published_state != 'true' && vars.NUGET_USER != '' }} + continue-on-error: true + uses: NuGet/login@8d196754b4036150537f80ac539e15c2f1028841 # v1.2.0 + with: + user: ${{ vars.NUGET_USER }} + + - name: Check release credentials id: preflight env: PACKAGE_ID: ${{ needs.test.outputs.package_id }} PACKAGE_VERSION: ${{ needs.test.outputs.version }} + PUBLISHED_STATE: ${{ steps.version.outputs.published_state }} + PUBLISHED_VERSION: ${{ steps.version.outputs.published_version }} + NUGET_OIDC_KEY: ${{ steps.nuget-login.outcome == 'success' && steps.nuget-login.outputs.NUGET_API_KEY || '' }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} NUGET_USER: ${{ vars.NUGET_USER }} @@ -54,7 +75,7 @@ jobs: pushToNuget: needs: [test, releasePreflight] runs-on: ubuntu-24.04 - timeout-minutes: 10 + timeout-minutes: 30 permissions: contents: read id-token: write @@ -76,18 +97,26 @@ jobs: - name: Log in to NuGet with trusted publishing id: nuget-login - if: ${{ needs.releasePreflight.outputs.auth == 'trusted-publishing' && needs.releasePreflight.outputs.publishRequired == 'true' }} + if: ${{ needs.releasePreflight.outputs.publishRequired == 'true' && vars.NUGET_USER != '' }} + continue-on-error: 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 }} + NUGET_USER: ${{ vars.NUGET_USER }} PUBLISH_REQUIRED: ${{ needs.releasePreflight.outputs.publishRequired }} - NUGET_API_KEY: ${{ steps.nuget-login.outputs.NUGET_API_KEY || secrets.NUGET_TOKEN }} + NUGET_OIDC_KEY: ${{ steps.nuget-login.outcome == 'success' && steps.nuget-login.outputs.NUGET_API_KEY || '' }} + NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} run: .github/scripts/push-nuget-package.sh "$RUNNER_TEMP/cpp-nuget"/*.nupkg + - name: Verify the public NuGet package + env: + PACKAGE_ID: ${{ needs.test.outputs.package_id }} + PACKAGE_VERSION: ${{ needs.test.outputs.version }} + run: node .github/scripts/preflight-nuget-release.mjs wait-for-package + # Waits for the push, so a release always has its package on nuget.org. publishRelease: needs: [test, pushToNuget] diff --git a/README.md b/README.md index 8176a0a..a617567 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,12 @@ Forked from: [Konard/LinksPlatform/Platform/Platform.Data.Core/Collections](http NuGet package: [Platform.Collections.Methods](https://www.nuget.org/packages/Platform.Collections.Methods) +Use version `1.0.1` or later on .NET 8 and later. It supports the +`Platform.Collections.Methods.Trees` and `Platform.Collections.Methods.Lists` +namespaces used in `0.7.3`. The old `1.0.0` package is unlisted. Exact version +references can still restore it, so update those references explicitly. Pin +`0.7.3` while waiting for `1.0.1` to appear on NuGet or if you target .NET 7. + ## [Documentation](https://linksplatform.github.io/Collections.Methods) [PDF file](https://linksplatform.github.io/Collections.Methods/csharp/Platform.Collections.Methods.pdf) @@ -316,14 +322,21 @@ 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 +1. On nuget.org, sign in as an individual who can publish the packages. Create + policies for `linksplatform/Collections.Methods`. Select the package owner + and grant **Push only new versions** for `Platform.Collections.Methods` + in `csharp.yml` and `Platform.Collections.Methods.TemplateLibrary` in + `deploy-cpp.yml`. Leave the optional environment field blank. +2. Set the GitHub repository variable `NUGET_USER` to the NuGet username that + created both policies. For organization-owned packages, use the individual + policy creator's username. + +To enable fallback, set `NUGET_TOKEN` to a NuGet API key with push scope for the +packages. The workflows use it when trusted publishing is unconfigured or NuGet +cannot issue or authorize its key. Pull requests verify the packed package with +an isolated consumer. The release verifies the public listing, and the C# release +also builds that consumer from nuget.org. If both credentials fail on `main`, +correct the policy or replace the key in the repository settings, then rerun +the failed jobs. Dependabot pull requests are merged automatically with the `DEPENDABOT_AUTO_MERGE_TOKEN` secret once "Allow auto-merge" is enabled. From c2e163fc329323ebbfaf06af939551da9c1c5608 Mon Sep 17 00:00:00 2001 From: konard Date: Mon, 30 Nov 2026 06:08:30 +0000 Subject: [PATCH 4/6] Check C++ release credentials before building the package --- .github/scripts/cpp-workflow-policy.test.mjs | 4 +++- .github/scripts/preflight-nuget-release.mjs | 8 +++++++- .github/scripts/preflight-nuget-release.test.mjs | 9 +++++++++ .github/workflows/deploy-cpp.yml | 10 ++++------ 4 files changed, 23 insertions(+), 8 deletions(-) diff --git a/.github/scripts/cpp-workflow-policy.test.mjs b/.github/scripts/cpp-workflow-policy.test.mjs index 2f11304..a220ea0 100644 --- a/.github/scripts/cpp-workflow-policy.test.mjs +++ b/.github/scripts/cpp-workflow-policy.test.mjs @@ -78,7 +78,9 @@ test("packs with dotnet and verifies the package on every run", () => { 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("test"), /needs: releasePreflight/); + assert.doesNotMatch(deployJobs.get("releasePreflight"), /needs: test/); + assert.match(deployJobs.get("releasePreflight"), /NUSPEC: .*TemplateLibrary\.nuspec/); assert.match(deployJobs.get("releasePreflight"), /preflight-nuget-release\.mjs check-version/); assert.match(deployJobs.get("releasePreflight"), /github\.ref == 'refs\/heads\/main'/); assert.match(deployJobs.get("releasePreflight"), /continue-on-error: true\n +uses: NuGet\/login@/); diff --git a/.github/scripts/preflight-nuget-release.mjs b/.github/scripts/preflight-nuget-release.mjs index b8dc3c6..2a4e8db 100644 --- a/.github/scripts/preflight-nuget-release.mjs +++ b/.github/scripts/preflight-nuget-release.mjs @@ -15,7 +15,7 @@ * the push scope for an existing package. The verification key returned by * the symbol-package endpoint does not retain the original package glob. * - * Environment: PACKAGE_ID, PACKAGE_VERSION (or CSPROJ to read both), + * Environment: PACKAGE_ID, PACKAGE_VERSION (or CSPROJ or NUSPEC to read both), * GITHUB_TOKEN, NUGET_TOKEN, NUGET_USER, NUGET_OIDC_KEY, NUGET_INDEX_URL and * NUGET_GALLERY_URL and NUGET_REGISTRATION_URL (tests), VERBOSE=1 or * RUNNER_DEBUG=1 for diagnostic output. @@ -25,6 +25,7 @@ import { appendFileSync, readFileSync } from "node:fs"; import { setTimeout as delay } from "node:timers/promises"; +import { readPackageInfo } from "./pack-cpp-nuget.mjs"; const defaultIndexUrl = "https://api.nuget.org/v3-flatcontainer"; const defaultGalleryUrl = "https://www.nuget.org"; @@ -182,6 +183,11 @@ const readPackage = (environment) => { packageId ||= project.packageId; version ||= project.version; } + if (environment.NUSPEC) { + const project = readPackageInfo(readFileSync(environment.NUSPEC, "utf8")); + packageId ||= project.id; + version ||= project.version; + } return { packageId, version }; }; diff --git a/.github/scripts/preflight-nuget-release.test.mjs b/.github/scripts/preflight-nuget-release.test.mjs index 3e2b3bd..207f9f4 100644 --- a/.github/scripts/preflight-nuget-release.test.mjs +++ b/.github/scripts/preflight-nuget-release.test.mjs @@ -5,6 +5,7 @@ import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; +import { nuspecPath } from "./pack-cpp-nuget.mjs"; import { evaluateRelease, fetchPublished, @@ -37,6 +38,14 @@ test("queries the lower-case flat-container index", () => { ); }); +test("reads the C++ package identity before building its package", async () => { + const { calls, fetchImpl } = gallery({ + "GET https://api.nuget.org/v3-flatcontainer/platform.collections.methods.templatelibrary/index.json": [200, { versions: ["0.3.0"] }], + }); + assert.equal(await run({ NUSPEC: nuspecPath }, fetchImpl, "check-version"), 0); + assert.equal(calls.length, 1); +}); + test("detects published, unpublished, unknown and unreachable packages", async () => { const query = (fetchImpl) => fetchPublished({ packageId: "P", version: "1.0.0-Beta", fetchImpl }); diff --git a/.github/workflows/deploy-cpp.yml b/.github/workflows/deploy-cpp.yml index c60ccb5..8c3ff00 100644 --- a/.github/workflows/deploy-cpp.yml +++ b/.github/workflows/deploy-cpp.yml @@ -27,16 +27,19 @@ env: jobs: test: + needs: releasePreflight + if: ${{ !cancelled() && (needs.releasePreflight.result == 'success' || github.ref != 'refs/heads/main') }} uses: ./.github/workflows/cpp-test.yml releasePreflight: - needs: test if: ${{ github.ref == 'refs/heads/main' }} runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: contents: read id-token: write + env: + NUSPEC: cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec outputs: publishRequired: ${{ steps.preflight.outputs.publish_required }} steps: @@ -46,9 +49,6 @@ jobs: - name: Check public package version id: version - env: - PACKAGE_ID: ${{ needs.test.outputs.package_id }} - PACKAGE_VERSION: ${{ needs.test.outputs.version }} run: node .github/scripts/preflight-nuget-release.mjs check-version - name: Log in to NuGet for release preflight @@ -62,8 +62,6 @@ jobs: - name: Check release credentials id: preflight env: - PACKAGE_ID: ${{ needs.test.outputs.package_id }} - PACKAGE_VERSION: ${{ needs.test.outputs.version }} PUBLISHED_STATE: ${{ steps.version.outputs.published_state }} PUBLISHED_VERSION: ${{ steps.version.outputs.published_version }} NUGET_OIDC_KEY: ${{ steps.nuget-login.outcome == 'success' && steps.nuget-login.outputs.NUGET_API_KEY || '' }} From 48fe354ed2462fd7fd4f1a0ee5b91973851d1a3a Mon Sep 17 00:00:00 2001 From: konard Date: Mon, 30 Nov 2026 06:13:26 +0000 Subject: [PATCH 5/6] Preserve the protected size balanced tree attach counter --- .../SizeBalancedTreeRotationTests.cs | 23 +++++++++++++++++++ .../Trees/SizeBalancedTreeMethods.cs | 18 +++++++++++++++ examples/NuGetConsumer/CollectionMethods.cs | 5 ++++ 3 files changed, 46 insertions(+) diff --git a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs index a1aee32..d6785aa 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs @@ -19,6 +19,29 @@ public class SizeBalancedTreeRotationTests public static IEnumerable Workloads => new[] { "Ascending", "Descending", "Random", "InterleavedHotAndCold", "AlternatingEnds" }.Select(w => new object[] { w }); + [Fact] + public void AttachCounterRemainsAvailableToDerivedTrees() + { + var tree = new TreeWithAttachCounter(); + Assert.Equal(0, tree.AttachCount); + + tree.Attach(ref tree.Root, 1); + Assert.Equal(1, tree.AttachCount); + + tree.Attach(ref tree.Root, 2); + Assert.Equal(0, tree.AttachCount); + + tree.Attach(ref tree.Root, 3); + Assert.Equal(1, tree.AttachCount); + } + + private sealed class TreeWithAttachCounter : SizeBalancedTree + { + public TreeWithAttachCounter() : base(4) { } + + public int AttachCount => attachCount; + } + /// /// An attach rotates if and only if the plain binary search tree insertion would break a size balanced tree property. /// Присоединение делает поворот тогда и только тогда, когда простая вставка в двоичное дерево поиска нарушила бы свойство дерева, сбалансированного по размеру. diff --git a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs index 77a5f08..cc542ed 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs @@ -30,6 +30,24 @@ namespace Platform.Collections.Methods.Trees /// public abstract class SizeBalancedTreeMethods : SizedBinaryTreeMethodsBase where TElement: IUnsignedNumber, IComparisonOperators { + /// + /// Counts attachments for compatibility with derived trees. The counter resets after every second attachment. + /// + protected int attachCount; + + protected override void BeforeAttach() + { + attachCount++; + } + + protected override void AfterAttach() + { + if (attachCount > 1) + { + attachCount = 0; + } + } + /// /// /// Attaches the node to the subtree with the specified root and restores the size balanced tree properties on the way back up. diff --git a/examples/NuGetConsumer/CollectionMethods.cs b/examples/NuGetConsumer/CollectionMethods.cs index 68b3ef4..f821b4d 100644 --- a/examples/NuGetConsumer/CollectionMethods.cs +++ b/examples/NuGetConsumer/CollectionMethods.cs @@ -36,3 +36,8 @@ public static void AppendToLists( relativeOpen.AttachAsLast(list, node); } } + +internal abstract class SizeBalancedTreeConsumer : SizeBalancedTreeMethods +{ + protected int AttachCount => attachCount; +} From d98ef7913176659cf2ac444b843e08643fae9431 Mon Sep 17 00:00:00 2001 From: konard Date: Mon, 30 Nov 2026 06:13:50 +0000 Subject: [PATCH 6/6] Address static analysis feedback on the NuGet consumer --- README.md | 2 +- examples/NuGetConsumer/CollectionMethods.cs | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a617567..29c23ce 100644 --- a/README.md +++ b/README.md @@ -324,7 +324,7 @@ first: 1. On nuget.org, sign in as an individual who can publish the packages. Create policies for `linksplatform/Collections.Methods`. Select the package owner - and grant **Push only new versions** for `Platform.Collections.Methods` + and grant __Push only new versions__ for `Platform.Collections.Methods` in `csharp.yml` and `Platform.Collections.Methods.TemplateLibrary` in `deploy-cpp.yml`. Leave the optional environment field blank. 2. Set the GitHub repository variable `NUGET_USER` to the NuGet username that diff --git a/examples/NuGetConsumer/CollectionMethods.cs b/examples/NuGetConsumer/CollectionMethods.cs index f821b4d..9286bf3 100644 --- a/examples/NuGetConsumer/CollectionMethods.cs +++ b/examples/NuGetConsumer/CollectionMethods.cs @@ -4,15 +4,16 @@ public static class CollectionMethods { - public static void MoveNode( + public static (uint SourceRoot, uint DestinationRoot) MoveNode( SizedAndThreadedAVLBalancedTreeMethods source, - ref uint sourceRoot, + uint sourceRoot, RecursionlessSizeBalancedTreeMethods destination, - ref uint destinationRoot, + uint destinationRoot, uint node) { source.Detach(ref sourceRoot, node); destination.Attach(ref destinationRoot, node); + return (sourceRoot, destinationRoot); } public static string FormatTree(SizedBinaryTreeMethodsBase tree, uint root)