From 84ec9565578e04f60128b246b799931da80e58cc Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Wed, 25 Nov 2026 18:26:48 +0100 Subject: [PATCH] Follow what the pull request itself changes, not the last release The check, the labels and the comment follow the pull request's committed API against its base branch, framework by framework, so a pull request is not held back by a breaking change main already has or by the pull requests below it in a stack. The new api-diff command compares two directories of committed .api files; the action runs it for the pull request and for each open pull request below it. The comparison with the last release stays in the comment, collapsed, with the pull requests that introduced its changes, and a change that is the same in every target framework is listed once. Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 2 +- README.md | 12 + action.yml | 88 +++++++- .../skills/assembly-differ/SKILL.md | 2 + .../ApiFiles/ApiDiffCommand.cs | 208 ++++++++++++++++++ src/assembly-differ/Program.cs | 1 + src/assembly-differ/PullRequests/Comment.cs | 149 +++++++++++-- .../PullRequests/PullRequestCommand.cs | 45 +++- ..._what_a_removed_method_breaks.verified.txt | 7 + ...he_pull_request_comment_reads.verified.txt | 23 ++ .../Help.pull-request.cc54f021.verified.txt | 3 + .../Help.root.460a906e.verified.txt | 2 + ...led_whatever_the_release_says.verified.txt | 36 +++ ...ch_the_stack_below_it_changed.verified.txt | 27 +++ tests/assembly-differ.Tests/ApiDiffTests.cs | 92 ++++++++ .../assembly-differ.Tests/PullRequestTests.cs | 106 +++++++++ 16 files changed, 776 insertions(+), 27 deletions(-) create mode 100644 src/assembly-differ/ApiFiles/ApiDiffCommand.cs create mode 100644 tests/assembly-differ.Tests/.snapshots/ApiDiffTests/Says_what_a_removed_method_breaks.verified.txt create mode 100644 tests/assembly-differ.Tests/.snapshots/ApiDiffTests/Writes_the_report_the_pull_request_comment_reads.verified.txt create mode 100644 tests/assembly-differ.Tests/.snapshots/PullRequestTests/A_pull_request_that_breaks_the_api_fails_and_is_labelled_whatever_the_release_says.verified.txt create mode 100644 tests/assembly-differ.Tests/.snapshots/PullRequestTests/A_pull_request_that_changes_nothing_passes_however_much_the_stack_below_it_changed.verified.txt create mode 100644 tests/assembly-differ.Tests/ApiDiffTests.cs diff --git a/AGENTS.md b/AGENTS.md index b2bb5fe..84f42d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,7 +21,7 @@ distroless container (`ghcr.io/nullean/assembly-differ`) and a GitHub Action (`a | `benchmarks/Nullean.PublicApi.Benchmarks` | BenchmarkDotNet: reading, writing, parsing and comparing System.Collections.Immutable and CoreLib, with allocations. `dotnet run -c Release --project benchmarks/Nullean.PublicApi.Benchmarks -- --filter '*' --inProcess` (in process: BenchmarkDotNet 0.15 does not know net11.0 yet) | | `build/scripts` | the F# build ([Runna.Fs](https://www.nuget.org/packages/Runna.Fs), net11.0) the `mise` tasks and CI call | | `build/keys` | the strong-name key the tool's and the libraries' assemblies are signed with | -| `action.yml` | the GitHub Action: installs the tool, compares the libraries with their latest release, optionally checks the committed `api/` files (`api-files`), and reports both in one pull request comment through `pull-request`; the deprecated `first`/`second` inputs still run the `edge` container image | +| `action.yml` | the GitHub Action: installs the tool, compares the libraries with their latest release, optionally checks the committed `api/` files (`api-files`), compares a pull request's committed API with its base branch's (`api-diff`, also for each pull request of a stack below it) so the check follows what the pull request itself changes, and reports all of it in one comment through `pull-request`; the deprecated `first`/`second` inputs still run the `edge` container image | ## Commands diff --git a/README.md b/README.md index 52da675..258a6bd 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,7 @@ bundles does not count as your API; `--all-assemblies` compares every assembly t | `release ` | a new build, as a `.nupkg`, a `.dll` or a directory, with the release before it; pass `--package` and `--version` unless `` is a `.nupkg` | | `files ` | two local builds, each a `.dll`, a directory of dlls or a `.nupkg` | | `api [path]` | nothing: writes the public API as `.api` files, and `--verify` checks committed ones against the build (see [Public API files](#public-api-files)) | +| `api-diff ` | two directories of committed `.api` files, such as the base branch's `api/` and a pull request's: what changed, by path, with no build, and the same change in every target framework once | | `upgrades` | in a solution, every package it references directly that has a newer release, and what updating each breaks in your code | | `nuget [] []` | in a solution, the version your projects resolve with the latest release, or with ``: what updating would change; anywhere, two published versions | | `projects` | every library project in the directory against its latest release; what runs without a command | @@ -231,6 +232,16 @@ jobs: The comment lists every assembly it compared, the ones without changes too, so a run that finds nothing says so: "All good: the public API is unchanged." A shallow checkout builds the libraries without their tags, and a version derived from tags (MinVer, Nerdbank.GitVersioning) then differs from the release in its own version and in the version of the assemblies it references: check out with `fetch-depth: 0`. +**What the check follows.** With `api-files`, the check, the release label and the comment follow what the pull request itself +changes: its committed API against the committed API of its base branch, target framework by target framework, so a +pull request is never held back by a breaking change `main` already has and has not released, or by the pull requests +below it in a stack. The comparison with the latest release is still in the comment, collapsed and marked as +information, and for a stacked pull request it says which of the pull requests below introduced the changes. A change +that is the same in every target framework is listed once, and one that only some frameworks have, such as code under +`#if NET8_0`, is listed apart with its frameworks. Without `api-files` there is no committed API to compare with, and the +check follows the comparison with the latest release. The action needs the `gh` CLI, as the hosted runners have, and +reads the base branch and the open pull requests whose branches the stack is made of. + Without `package`, the action compares every library project of the solution with the latest release of its package, the way running the tool without a command does. Give `package: build/output/MyLib.1.3.0.nupkg` to compare a packed package with the release before it instead. It installs the tool with `dotnet tool`, so it needs the .NET 10 SDK or @@ -243,6 +254,7 @@ later on the runner, the one your build uses. | `target` | | only these assemblies, one per line | | `framework` | | the target framework to compare | | `api-files` | | the directory of committed `.api` files, such as `api`: they are checked against the build too, in the same comment, and the action fails when they differ; see [Public API files](#public-api-files) | +| `base-comparison` | `true` | on a pull request with `api-files`, follow what the pull request itself changes against its base branch; `false` follows the comparison with the latest release | | `api-split` | `none` | how the committed files were split: `none`, `namespace` or `top-level-namespace` | | `fail-on` | `major` | fail when the suggested change is at least this, unless the pull request has `allow-label`; `none` never fails | | `allow-label` | `breaking-allowed` | the label that lets a change at `fail-on` through | diff --git a/action.yml b/action.yml index 1337749..da93915 100644 --- a/action.yml +++ b/action.yml @@ -25,6 +25,10 @@ inputs: description: 'The directory of committed .api files, as assembly-differ api -o wrote them. When set, they are checked against the build too, in the same comment, and the action fails when they differ. Leave empty to skip.' required: false default: '' + base-comparison: + description: 'On a pull request with api-files, compare its committed API with its base branch: the check, the labels and the comment then follow what this pull request itself changes, and the comparison with the latest release is shown for information. Set to false to follow the comparison with the latest release.' + required: false + default: 'true' api-split: description: 'How the committed .api files were split: none, namespace or top-level-namespace.' required: false @@ -84,7 +88,7 @@ inputs: outputs: suggested-change: - description: 'The suggested version change: None, Patch, Minor or Major.' + description: 'The suggested version change: None, Patch, Minor or Major. What the pull request itself changes against its base branch when api-files is set, otherwise the comparison with the latest release.' value: ${{ steps.report.outputs.suggested-change }} breaking-changes: description: 'How many breaking changes were found.' @@ -177,6 +181,76 @@ runs: echo "code=$code" >> "$GITHUB_OUTPUT" if [ "$code" = "0" ]; then echo "matches=true" >> "$GITHUB_OUTPUT"; else echo "matches=false" >> "$GITHUB_OUTPUT"; fi + - name: Compare with the base branch + id: base + if: inputs.first == '' && inputs.api-files != '' && inputs.base-comparison == 'true' && github.event_name == 'pull_request' + shell: bash + working-directory: ${{ inputs.working-directory }} + env: + GH_TOKEN: ${{ inputs.token }} + REPOSITORY: ${{ github.repository }} + BASE_REF: ${{ github.event.pull_request.base.ref }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + API_FILES: ${{ inputs.api-files }} + run: | + # What this pull request changes in the committed API, against its base branch, and which pull requests below it in + # a stack changed the API before it. Nothing is built: the committed .api files of each commit are compared. + tool="$RUNNER_TEMP/assembly-differ-tool/assembly-differ" + work="$RUNNER_TEMP/assembly-differ-base" + rm -rf "$work" && mkdir -p "$work" + prefix="$(git rev-parse --show-prefix)${API_FILES#./}" + prefix="${prefix%/}" + header="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')" + + skip() { echo "::warning title=assembly-differ::$1; the check follows the comparison with the latest release"; exit 0; } + + # the committed API of a commit, in a directory of its own; nothing when the commit has none + export_api() { + mkdir -p "$2" + git -c "http.https://github.com/.extraheader=$header" fetch --quiet --no-tags --depth=1 origin "$1" || return 1 + git archive "$1" -- "$prefix" 2>/dev/null | tar -x -C "$2" || true + } + tip() { gh api "repos/$REPOSITORY/git/ref/heads/$1" --jq .object.sha; } + + base_sha=$(tip "$BASE_REF") || skip "could not read the base branch $BASE_REF" + export_api "$base_sha" "$work/base" || skip "could not fetch the base branch $BASE_REF" + "$tool" api-diff "$work/base/$prefix" "$API_FILES" --format json --output "$work/delta.json" || skip "could not compare with the base branch" + + # the pull requests below this one: the open ones whose branch is the base of the one above + numbers=(); titles=(); urls=(); shas=(); bases=() + cur="$BASE_REF" + owner="${REPOSITORY%%/*}" + for _ in $(seq 1 30); do + [ "$cur" = "$DEFAULT_BRANCH" ] && break + found=$(gh api "repos/$REPOSITORY/pulls?head=$owner:$cur&state=open&per_page=1" --jq '.[0] // empty | [.number, .title, .html_url, .head.sha, .base.ref] | @tsv') || break + [ -z "$found" ] && break + IFS=$'\t' read -r n title url sha base <<< "$found" + numbers+=("$n"); titles+=("$title"); urls+=("$url"); shas+=("$sha"); bases+=("$base") + cur="$base" + done + + base_name="\`$BASE_REF\`" + [ "${#numbers[@]}" -gt 0 ] && base_name="$base_name (#${numbers[0]})" + + # each of them against what it was based on, from the bottom of the stack up + echo '[]' > "$work/stack.json" + count=${#numbers[@]} + for ((i = count - 1; i >= 0; i--)); do + if [ "$i" -eq $((count - 1)) ]; then below_sha=$(tip "${bases[$i]}") || continue; else below_sha="${shas[$((i + 1))]}"; fi + export_api "$below_sha" "$work/below-$i" || continue + export_api "${shas[$i]}" "$work/at-$i" || continue + "$tool" api-diff "$work/below-$i/$prefix" "$work/at-$i/$prefix" --format json --output "$work/entry-$i.json" > /dev/null || continue + jq --argjson number "${numbers[$i]}" --arg title "${titles[$i]}" --arg url "${urls[$i]}" \ + '{number: $number, title: $title, url: $url, suggestedVersionChange: .suggestedVersionChange, breakingChanges: (.distinctBreakingChanges // .breakingChanges)}' \ + "$work/entry-$i.json" > "$work/entry-$i.line.json" + jq --slurpfile entry "$work/entry-$i.line.json" '. + $entry' "$work/stack.json" > "$work/stack.tmp" && mv "$work/stack.tmp" "$work/stack.json" + done + + echo "report=$work/delta.json" >> "$GITHUB_OUTPUT" + echo "stack=$work/stack.json" >> "$GITHUB_OUTPUT" + echo "name=$base_name" >> "$GITHUB_OUTPUT" + echo "suggested-change=$(jq -r .suggestedVersionChange "$work/delta.json")" >> "$GITHUB_OUTPUT" + - name: Report on the pull request id: report if: inputs.first == '' @@ -193,25 +267,31 @@ runs: LABELS: ${{ inputs.labels }} API_CODE: ${{ steps.api.outputs.code }} API_REPORT: ${{ steps.api.outputs.report }} + BASE_REPORT: ${{ steps.base.outputs.report }} + BASE_NAME: ${{ steps.base.outputs.name }} + BASE_STACK: ${{ steps.base.outputs.stack }} run: | report="$RUNNER_TEMP/assembly-differ/api-changes.json" if [ ! -f "$report" ]; then # nothing was compared, such as a solution whose libraries have no release yet echo "suggested-change=None" >> "$GITHUB_OUTPUT" echo "breaking-changes=0" >> "$GITHUB_OUTPUT" - [ -z "$API_CODE" ] && exit 0 + [ -z "$API_CODE" ] && [ -z "$BASE_REPORT" ] && exit 0 # the committed API files are still reported, and still fail the check mkdir -p "$RUNNER_TEMP/assembly-differ" echo '{"firstRelease":true,"suggestedVersionChange":"None","breakingChanges":0,"assemblies":[]}' > "$report" fi echo "report=$report" >> "$GITHUB_OUTPUT" - echo "suggested-change=$(jq -r .suggestedVersionChange "$report")" >> "$GITHUB_OUTPUT" - echo "breaking-changes=$(jq -r .breakingChanges "$report")" >> "$GITHUB_OUTPUT" + # on a pull request with a base branch to compare with, the outputs are what the pull request itself changes + deciding="${BASE_REPORT:-$report}" + echo "suggested-change=$(jq -r .suggestedVersionChange "$deciding")" >> "$GITHUB_OUTPUT" + echo "breaking-changes=$(jq -r '.distinctBreakingChanges // .breakingChanges' "$deciding")" >> "$GITHUB_OUTPUT" args=(pull-request "$report" --fail-on "$FAIL_ON" --allow-label "$ALLOW_LABEL" --major-label "$MAJOR_LABEL" --minor-label "$MINOR_LABEL" --patch-label "$PATCH_LABEL") [ "$COMMENT" != "true" ] && args+=(--no-comment) [ "$LABELS" != "true" ] && args+=(--no-labels) [ -n "$API_CODE" ] && args+=(--api-code "$API_CODE" --api-report "$API_REPORT") + [ -n "$BASE_REPORT" ] && args+=(--base-report "$BASE_REPORT" --base-name "$BASE_NAME" --stack "$BASE_STACK") set +e "$RUNNER_TEMP/assembly-differ-tool/assembly-differ" "${args[@]}" code=$? diff --git a/src/assembly-differ.skills/skills/assembly-differ/SKILL.md b/src/assembly-differ.skills/skills/assembly-differ/SKILL.md index 8769a1d..369c2ba 100644 --- a/src/assembly-differ.skills/skills/assembly-differ/SKILL.md +++ b/src/assembly-differ.skills/skills/assembly-differ/SKILL.md @@ -49,6 +49,8 @@ assemblies, and `--fail-on ` to exit with code 4 at or a `--include-unpackable` or `--project ` change that. - **`release` in a solution compares only the assemblies the solution builds**, not the dependencies a package bundles; `--all-assemblies` compares every assembly, `-t` names them. +- **`api-diff ` compares two directories of committed `.api` files** with no build, such as a base branch's + `api/` and a pull request's: what a pull request itself changes, whatever the last release says. - **A package with no earlier release is a first release**: nothing to compare, exit code 0 (`--require-baseline` fails instead). diff --git a/src/assembly-differ/ApiFiles/ApiDiffCommand.cs b/src/assembly-differ/ApiFiles/ApiDiffCommand.cs new file mode 100644 index 0000000..1a83f7a --- /dev/null +++ b/src/assembly-differ/ApiFiles/ApiDiffCommand.cs @@ -0,0 +1,208 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using Nullean.Argh; +using Nullean.PublicApi; + +namespace Differ.ApiFiles; + +/// Compares the committed .api files of two versions of a repository, without building or loading anything. +internal sealed class ApiDiffCommand +{ + /// What one API did: its name, the version change it calls for and the changes, by path. + internal sealed record Entry(string Name, SuggestedVersionChange Suggested, int Breaking, IReadOnlyList Changes); + + /// One change: what it is, and how far it reaches. + internal sealed record Item(string Text, string Change, SuggestedVersionChange Level); + + /// Compares the .api files in two directories: what changed from the old ones to the new ones, by path. + /// + /// Each API is compared with the one of the same name, so the files of one target framework are compared with the files + /// of the same framework. An API only the new directory has is added, a minor change, and one only the old directory + /// has is removed, a major one. Nothing is built, so it compares what two commits committed, such as the base of a + /// pull request and its head, and says what the pull request itself changes however much main has changed since the + /// last release. Always exits with 0 when it could compare; read the suggested version change from the report. + /// + /// The directory of the earlier .api files, such as the base branch's api/. + /// The directory of the later .api files. + /// text prints each change; json writes api-changes.json, with the APIs without changes too. + /// A file to write the json report to, besides the summary on the console. + /// assembly-differ api-diff base/api api + /// assembly-differ api-diff base/api api --format json --output api-delta.json + [CommandName("api-diff")] + public int ApiDiff( + [Argument] string oldDirectory, + [Argument] string newDirectory, + [AllowedValues("text", "json")] string format = "text", + string? output = null + ) + { + if (format == "json" && output is null) + { + Console.Error.WriteLine("[api] json is written to a file: pass --output"); + return 1; + } + try + { + var entries = Compare(oldDirectory, newDirectory, out var removed, out var added); + var worst = entries + .Select(e => e.Suggested) + .Append(removed.Count > 0 ? SuggestedVersionChange.Major : SuggestedVersionChange.None) + .Append(added.Count > 0 ? SuggestedVersionChange.Minor : SuggestedVersionChange.None) + .Max(); + var breaking = entries.Sum(e => e.Breaking) + removed.Count; + // the same change in every target framework is one change + var distinct = entries + .SelectMany(e => e.Changes.Where(c => c.Level == SuggestedVersionChange.Major).Select(c => (Library(e.Name), c.Text))) + .Distinct() + .Count() + removed.Count; + foreach (var entry in entries.Where(e => e.Changes.Count > 0)) + { + Console.WriteLine( + $"[api] {entry.Name}: {entry.Changes.Count} change{(entry.Changes.Count == 1 ? "" : "s")}, suggested version change: {entry.Suggested}" + ); + foreach (var item in entry.Changes) + Console.WriteLine($" {item.Text}"); + } + foreach (var name in removed) + Console.WriteLine($"[api] {name}: only in {oldDirectory}, so removed"); + foreach (var name in added) + Console.WriteLine($"[api] {name}: only in {newDirectory}, so added"); + var unchanged = entries.Count(e => e.Changes.Count == 0); + Console.WriteLine($"[api] {entries.Count} API{(entries.Count == 1 ? "" : "s")} compared, {unchanged} without changes"); + Console.WriteLine($"[api] Suggested version change: {worst}"); + if (output is not null) + { + File.WriteAllBytes(output, Json(entries, removed, added, worst, breaking, distinct)); + Console.WriteLine($"[api] Wrote {output}"); + } + return 0; + } + catch (Exception e) when (e is IOException or ArgumentException or FormatException or InvalidDataException) + { + Console.Error.WriteLine($"[api] {e.Message}"); + return 1; + } + } + + /// Compares the APIs in two directories, in name order; the names only one side has are returned apart. + internal static List Compare(string oldDirectory, string newDirectory, out List removed, out List added) + { + var oldFiles = ApiFileCommand.Existing(oldDirectory); + var newFiles = ApiFileCommand.Existing(newDirectory); + removed = []; + added = []; + var entries = new List(); + foreach (var name in oldFiles.Keys.Concat(newFiles.Keys).Select(Name).Distinct().OrderBy(n => n, StringComparer.Ordinal)) + { + var before = oldFiles.Where(f => Name(f.Key) == name).ToList(); + var after = newFiles.Where(f => Name(f.Key) == name).ToList(); + if (before.Count == 0) + { + added.Add(name); + continue; + } + if (after.Count == 0) + { + removed.Add(name); + continue; + } + if (before.Count == after.Count && before.All(f => newFiles.TryGetValue(f.Key, out var text) && text == f.Value)) + { + entries.Add(new Entry(name, SuggestedVersionChange.None, 0, [])); + continue; + } + + var oldDocument = ApiParser.Parse(before.Select(f => ((string?)Path.Combine(oldDirectory, f.Key), f.Value))); + var newDocument = ApiParser.Parse(after.Select(f => ((string?)Path.Combine(newDirectory, f.Key), f.Value))); + var result = Nullean.PublicApi.Diff.ApiComparison.Compare(oldDocument.Assembly, newDocument.Assembly); + var items = result + .Changes + .Select( + c => new Item( + ApiReport.Line(c), + c.Kind switch + { + Nullean.PublicApi.Diff.ApiChangeKind.Added => "added", + Nullean.PublicApi.Diff.ApiChangeKind.Removed => "removed", + _ => "modified", + }, + c.Level + ) + ) + .ToList(); + // files that differ while the API they describe is the same: only how they were written + entries.Add(new Entry(name, items.Count == 0 ? SuggestedVersionChange.None : result.Suggest(), result.Breaking.Count(), items)); + } + return entries; + } + + /// The report in the shape of api-changes.json, so the pull request comment renders it as it does the others. + private static byte[] Json( + IReadOnlyList entries, + IReadOnlyList removed, + IReadOnlyList added, + SuggestedVersionChange worst, + int breaking, + int distinct + ) + { + using var stream = new MemoryStream(); + using (var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true })) + { + json.WriteStartObject(); + json.WriteBoolean("firstRelease", false); + json.WriteString("suggestedVersionChange", worst.ToString()); + json.WriteNumber("breakingChanges", breaking); + json.WriteNumber("distinctBreakingChanges", distinct); + json.WriteStartArray("assemblies"); + foreach (var entry in entries) + { + json.WriteStartObject(); + json.WriteString("name", entry.Name); + json.WriteString("suggestedVersionChange", entry.Suggested.ToString()); + json.WriteNumber("breakingChanges", entry.Breaking); + json.WriteStartArray("changes"); + foreach (var item in entry.Changes) + { + json.WriteStartObject(); + json.WriteString("kind", "Declaration"); + json.WriteString("name", item.Text); + json.WriteString("change", item.Change); + json.WriteString("suggestedVersionChange", item.Level.ToString()); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteStartArray("removedAssemblies"); + foreach (var name in removed) + json.WriteStringValue(name); + json.WriteEndArray(); + json.WriteStartArray("addedAssemblies"); + foreach (var name in added) + json.WriteStringValue(name); + json.WriteEndArray(); + json.WriteEndObject(); + } + return stream.ToArray(); + } + + private static readonly System.Text.RegularExpressions.Regex FrameworkSuffix = new( + @"\.(net\d+(\.\d+)?|netstandard\d+\.\d+|netcoreapp\d+\.\d+)$", + System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant + ); + + /// The library an API belongs to, without the target framework its name may end in. + private static string Library(string name) => FrameworkSuffix.Replace(name, ""); + + /// The API a file belongs to: the folder of a split API, or the file's name. + private static string Name(string relative) => + relative.IndexOf('/') is var slash and >= 0 ? relative.Substring(0, slash) : relative.Substring(0, relative.Length - ".api".Length); +} diff --git a/src/assembly-differ/Program.cs b/src/assembly-differ/Program.cs index 0101c9f..0828b5b 100644 --- a/src/assembly-differ/Program.cs +++ b/src/assembly-differ/Program.cs @@ -11,6 +11,7 @@ app.Map(); app.Map(); app.Map(); +app.Map(); app.Map(); app.MapAndRootAlias(); diff --git a/src/assembly-differ/PullRequests/Comment.cs b/src/assembly-differ/PullRequests/Comment.cs index b7df37c..9611ce1 100644 --- a/src/assembly-differ/PullRequests/Comment.cs +++ b/src/assembly-differ/PullRequests/Comment.cs @@ -23,12 +23,22 @@ public static class Comment /// public sealed record ApiFiles(int Code, string Report); + /// A pull request below this one in a stack, and what it changed in the public API. + public sealed record StackEntry(int Number, string Title, string Url, string Suggested, int Breaking); + + /// + /// What the pull request itself changes: the comparison of its committed API with its base branch's, and the pull + /// requests below it in a stack that changed the API before it. + /// + public sealed record Delta(JsonElement Report, string BaseName, IReadOnlyList Stack); + public static string Render( JsonElement report, IReadOnlyCollection labels, Gate gate = Gate.None, string allowLabel = "", - ApiFiles? apiFiles = null + ApiFiles? apiFiles = null, + Delta? delta = null ) { var body = new StringBuilder(); @@ -48,27 +58,128 @@ public static string Render( break; } - if (report.TryGetProperty("firstRelease", out var first) && first.GetBoolean()) + if (delta is null) { - body.AppendLine("### API changes: first release"); - body.AppendLine(); - body.AppendLine("There is no earlier release to compare with."); + if (IsFirstRelease(report)) + { + body.AppendLine("### API changes: first release"); + body.AppendLine(); + body.AppendLine("There is no earlier release to compare with."); + } + else + WriteSection(body, report, "### API changes", group: false, "the public API is unchanged"); WriteApiFiles(body, apiFiles); return body.ToString(); } - var suggested = report.GetProperty("suggestedVersionChange").GetString(); - var breaking = report.GetProperty("breakingChanges").GetInt32(); - body.AppendLine($"### API changes: suggested version change **{suggested}**"); + // the pull request's own change leads: it is what the check and the labels follow + WriteSection( + body, + delta.Report, + "### API changes in this pull request", + group: true, + "this pull request does not change the public API", + $"Compared with the base branch {delta.BaseName}. " + ); + + // since the last release is information: what main already has, or what the pull requests below this one changed, + // does not fail this pull request body.AppendLine(); - var baseline = report.TryGetProperty("baseline", out var b) ? $"Compared with `{b.GetString()}`. " : ""; + if (IsFirstRelease(report)) + body.AppendLine("There is no earlier release to compare with."); + else + { + var cumulative = report.GetProperty("suggestedVersionChange").GetString(); + var cumulativeBreaking = report.GetProperty("breakingChanges").GetInt32(); + var since = report.TryGetProperty("baseline", out var baseline) ? $" (`{baseline.GetString()}`)" : ""; + body.AppendLine( + $"
Since the last release{since}: {cumulative}, {(cumulativeBreaking == 0 ? "no breaking changes" : Count(cumulativeBreaking, "breaking change"))}; for information, it does not fail this check" + ); + body.AppendLine(); + WriteSection(body, report, null, group: false, "the public API is unchanged"); + var introducing = delta.Stack.Where(s => s.Suggested != "None").ToList(); + if (introducing.Count > 0) + { + body.AppendLine(); + body.AppendLine("**Introduced by** the pull requests below this one:"); + body.AppendLine(); + body.AppendLine("| Pull request | Change | Breaking |"); + body.AppendLine("|---|---|---|"); + foreach (var entry in introducing) + body.AppendLine( + $"| [#{entry.Number}]({entry.Url}) {entry.Title.Replace("|", "\\|", StringComparison.Ordinal)} | {entry.Suggested} | {entry.Breaking} |" + ); + } + body.AppendLine(); + body.AppendLine("
"); + } + WriteApiFiles(body, apiFiles); + return body.ToString(); + } + + private static bool IsFirstRelease(JsonElement report) => report.TryGetProperty("firstRelease", out var first) && first.GetBoolean(); + + /// An assembly's name split into the assembly and its target framework, when the name ends in one: Lib.net8.0. + private static readonly System.Text.RegularExpressions.Regex Framework = new( + @"^(?.+?)\.(?net\d+(?:\.\d+)?|netstandard\d+\.\d+|netcoreapp\d+\.\d+)$", + System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant + ); + + /// One or more assemblies of the report with the same changes: the frameworks of one library, usually. + private sealed record Group(string Label, JsonElement First, int Count); + + /// + /// The assemblies of a report, with those that have the same changes written once: a change that is the same in + /// every target framework is one change, not one per framework, and one only some frameworks have stands apart. + /// + private static List Grouped(IReadOnlyList assemblies, bool group) + { + if (!group) + return assemblies.Select(a => new Group(a.GetProperty("name").GetString()!, a, 1)).ToList(); + var groups = new List<(string Assembly, string Signature, List Frameworks, JsonElement First)>(); + foreach (var assembly in assemblies) + { + var name = assembly.GetProperty("name").GetString()!; + var match = Framework.Match(name); + var library = match.Success ? match.Groups["assembly"].Value : name; + var framework = match.Success ? match.Groups["tfm"].Value : ""; + var signature = assembly.GetProperty("changes").GetRawText(); + var existing = groups.FindIndex(g => g.Assembly == library && g.Signature == signature); + if (existing >= 0) + groups[existing].Frameworks.Add(framework); + else + groups.Add((library, signature, [framework], assembly)); + } + return groups.Select( + g => new Group( + g.Frameworks.All(f => f.Length == 0) ? g.Assembly : $"{g.Assembly} ({string.Join(", ", g.Frameworks.Where(f => f.Length > 0))})", + g.First, + g.Frameworks.Count + ) + ).ToList(); + } + + /// The summary line, the assemblies without changes and the details of the ones with, for one report. + private static void WriteSection(StringBuilder body, JsonElement report, string? heading, bool group, string allGood, string compared = "") + { + var suggested = report.GetProperty("suggestedVersionChange").GetString(); var assemblies = report.GetProperty("assemblies").EnumerateArray().ToList(); + var groups = Grouped(assemblies, group); + // a change in every framework counts once + var breaking = group ? groups.Sum(g => g.First.GetProperty("breakingChanges").GetInt32()) : report.GetProperty("breakingChanges").GetInt32(); + if (heading is not null) + { + body.AppendLine($"{heading}: suggested version change **{suggested}**"); + body.AppendLine(); + } + var baseline = compared.Length > 0 + ? compared + : report.TryGetProperty("baseline", out var b) && heading is not null ? $"Compared with `{b.GetString()}`. " : ""; var removed = Names(report, "removedAssemblies").ToList(); var added = Names(report, "addedAssemblies").ToList(); var unchanged = assemblies.Count > 0 && removed.Count == 0 && added.Count == 0 && assemblies.All(a => a.GetProperty("changes").GetArrayLength() == 0); body.AppendLine( - baseline + - (breaking > 0 ? $"⚠️ {Count(breaking, "breaking change")}." : unchanged ? "✅ All good: the public API is unchanged." : "No breaking changes.") + baseline + (breaking > 0 ? $"⚠️ {Count(breaking, "breaking change")}." : unchanged ? $"✅ All good: {allGood}." : "No breaking changes.") ); foreach (var name in removed) @@ -77,27 +188,27 @@ public static string Render( body.AppendLine($"- 🌟 assembly `{name}` is added"); // what was compared is listed too, so it is clear the tool picked up what was expected - var untouched = assemblies.Where(a => a.GetProperty("changes").GetArrayLength() == 0).ToList(); + var untouched = groups.Where(g => g.First.GetProperty("changes").GetArrayLength() == 0).ToList(); if (untouched.Count > 0) { body.AppendLine(); - foreach (var assembly in untouched) - body.AppendLine($"- ✅ **{assembly.GetProperty("name").GetString()}**: no changes"); + foreach (var item in untouched) + body.AppendLine($"- ✅ **{item.Label}**: no changes"); } var truncated = 0; - foreach (var assembly in assemblies) + foreach (var item in groups) { - var changes = assembly.GetProperty("changes"); + var changes = item.First.GetProperty("changes"); if (changes.GetArrayLength() == 0) continue; - var assemblyBreaking = assembly.GetProperty("breakingChanges").GetInt32(); + var assemblyBreaking = item.First.GetProperty("breakingChanges").GetInt32(); var details = new StringBuilder(); foreach (var change in changes.EnumerateArray()) truncated += WriteChange(details, change, 0, body.Length); body.AppendLine(); body.AppendLine( - $"
{assembly.GetProperty("name").GetString()}: {assembly.GetProperty("suggestedVersionChange").GetString()}, " + + $"
{item.Label}: {item.First.GetProperty("suggestedVersionChange").GetString()}, " + $"{(assemblyBreaking == 0 ? "no breaking changes" : Count(assemblyBreaking, "breaking change"))}" ); body.AppendLine(); @@ -109,8 +220,6 @@ public static string Render( body.AppendLine().AppendLine( $"{Count(truncated, "more change")} did not fit in this comment; the job summary and `api-changes.json` have them all." ); - WriteApiFiles(body, apiFiles); - return body.ToString(); } /// The section on the committed .api files, when they were checked. diff --git a/src/assembly-differ/PullRequests/PullRequestCommand.cs b/src/assembly-differ/PullRequests/PullRequestCommand.cs index e4d069d..fc2d566 100644 --- a/src/assembly-differ/PullRequests/PullRequestCommand.cs +++ b/src/assembly-differ/PullRequests/PullRequestCommand.cs @@ -40,6 +40,9 @@ internal sealed class PullRequestCommand /// The label for a Major change, matching release-drafter's; empty sets none. /// The label for a Minor change; empty sets none. /// The label for a Patch change; empty sets none. + /// The api-changes.json of api-diff for this pull request against its base branch. When given, the labels and --fail-on follow this change, the pull request's own, and the report above is shown as the change since the last release, for information. + /// What the base is called in the comment, such as the branch and its pull request; used with --base-report. + /// A json array of the pull requests below this one in a stack, each with number, title, url, suggestedVersionChange and breakingChanges, to say which introduced the changes since the last release; used with --base-report. /// The exit code of api --verify, to put the check of the committed .api files in the same comment: 0 when they match the build, 5 when they do not. The check fails on anything else. /// What api --verify printed, for the comment; used with --api-code. /// Leave the comment alone. @@ -57,6 +60,9 @@ public async Task PullRequest( string majorLabel = "breaking", string minorLabel = "feature", string patchLabel = "", + string? baseReport = null, + string? baseName = null, + string? stack = null, int? apiCode = null, string? apiReport = null, bool noComment = false, @@ -73,7 +79,21 @@ public async Task PullRequest( using var document = JsonDocument.Parse(await File.ReadAllTextAsync(report)); var root = document.RootElement; - var suggestedText = root.GetProperty("suggestedVersionChange").GetString(); + // the pull request's own change, against its base, decides the labels and the check when there is one + JsonDocument? baseDocument = null; + Comment.Delta? delta = null; + if (baseReport is not null) + { + if (!File.Exists(baseReport)) + { + Console.Error.WriteLine($"[diff] no report at {baseReport}; write one with api-diff --format json"); + return 1; + } + baseDocument = JsonDocument.Parse(await File.ReadAllTextAsync(baseReport)); + delta = new Comment.Delta(baseDocument.RootElement, baseName ?? "", await StackFrom(stack)); + } + var deciding = delta?.Report ?? root; + var suggestedText = deciding.GetProperty("suggestedVersionChange").GetString(); var suggested = Enum.Parse(suggestedText!, ignoreCase: true); var label = suggested switch { @@ -111,7 +131,7 @@ public async Task PullRequest( var apiFiles = apiCode is { } code ? new Comment.ApiFiles(code, apiReport is not null && File.Exists(apiReport) ? await File.ReadAllTextAsync(apiReport) : "") : null; - var body = Comment.Render(root, wanted, gate, allowLabel, apiFiles); + var body = Comment.Render(root, wanted, gate, allowLabel, apiFiles, delta); var summary = Env("GITHUB_STEP_SUMMARY"); if (!string.IsNullOrEmpty(summary)) @@ -169,6 +189,27 @@ public async Task PullRequest( } } + /// The pull requests below this one, from the json the action wrote. + private static async Task> StackFrom(string? path) + { + if (path is null || !File.Exists(path)) + return []; + using var document = JsonDocument.Parse(await File.ReadAllTextAsync(path)); + return document + .RootElement + .EnumerateArray() + .Select( + e => new Comment.StackEntry( + e.GetProperty("number").GetInt32(), + e.GetProperty("title").GetString() ?? "", + e.GetProperty("url").GetString() ?? "", + e.GetProperty("suggestedVersionChange").GetString() ?? "None", + e.GetProperty("breakingChanges").GetInt32() + ) + ) + .ToList(); + } + /// The exit code: 4 when a change at --fail-on is not allowed, with a line saying why and what to do. private static int Verdict(Gate gate, SuggestedVersionChange suggested, SuggestedVersionChange failOn, string allowLabel, bool onPullRequest) { diff --git a/tests/assembly-differ.Tests/.snapshots/ApiDiffTests/Says_what_a_removed_method_breaks.verified.txt b/tests/assembly-differ.Tests/.snapshots/ApiDiffTests/Says_what_a_removed_method_breaks.verified.txt new file mode 100644 index 0000000..9bd3afd --- /dev/null +++ b/tests/assembly-differ.Tests/.snapshots/ApiDiffTests/Says_what_a_removed_method_breaks.verified.txt @@ -0,0 +1,7 @@ +exit code: 0 +--- stdout +[api] Lib: 1 change, suggested version change: Major + Lib › Widget › Draw() removed void Draw() [major: breaks callers, compiled code and source] +[api] 1 API compared, 0 without changes +[api] Suggested version change: Major +--- stderr diff --git a/tests/assembly-differ.Tests/.snapshots/ApiDiffTests/Writes_the_report_the_pull_request_comment_reads.verified.txt b/tests/assembly-differ.Tests/.snapshots/ApiDiffTests/Writes_the_report_the_pull_request_comment_reads.verified.txt new file mode 100644 index 0000000..ab6c619 --- /dev/null +++ b/tests/assembly-differ.Tests/.snapshots/ApiDiffTests/Writes_the_report_the_pull_request_comment_reads.verified.txt @@ -0,0 +1,23 @@ +{ + "firstRelease": false, + "suggestedVersionChange": "Major", + "breakingChanges": 1, + "distinctBreakingChanges": 1, + "assemblies": [ + { + "name": "Lib", + "suggestedVersionChange": "Major", + "breakingChanges": 1, + "changes": [ + { + "kind": "Declaration", + "name": "Lib \u203A Widget \u203A Draw() removed void Draw() [major: breaks callers, compiled code and source]", + "change": "removed", + "suggestedVersionChange": "Major" + } + ] + } + ], + "removedAssemblies": [], + "addedAssemblies": [] +} diff --git a/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.pull-request.cc54f021.verified.txt b/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.pull-request.cc54f021.verified.txt index 1004e11..75ab471 100644 --- a/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.pull-request.cc54f021.verified.txt +++ b/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.pull-request.cc54f021.verified.txt @@ -17,6 +17,9 @@ Options: --major-label The label for a Major change, matching release-drafter's; empty sets none. [default: breaking] --minor-label The label for a Minor change; empty sets none. [default: feature] --patch-label The label for a Patch change; empty sets none. [default: ] + --base-report The api-changes.json of api-diff for this pull request against its base branch. When given, the labels and --fail-on follow this change, the pull request's own, and the report above is shown as the change since the last release, for information. [default: null] + --base-name What the base is called in the comment, such as the branch and its pull request; used with --base-report. [default: null] + --stack A json array of the pull requests below this one in a stack, each with number, title, url, suggestedVersionChange and breakingChanges, to say which introduced the changes since the last release; used with --base-report. [default: null] --api-code The exit code of api --verify, to put the check of the committed .api files in the same comment: 0 when they match the build, 5 when they do not. The check fails on anything else. [default: default] --api-report What api --verify printed, for the comment; used with --api-code. [default: null] --no-comment Leave the comment alone. diff --git a/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.root.460a906e.verified.txt b/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.root.460a906e.verified.txt index b80387e..e0624e4 100644 --- a/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.root.460a906e.verified.txt +++ b/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.root.460a906e.verified.txt @@ -16,6 +16,8 @@ Global options: Commands: api Writes the public API of a build as .api files, or checks committed ones against it. + api-diff Compares the .api files in two directories: what changed from + the old ones to the new ones, by path. files Compares two local builds: dlls, directories of dlls, or .nupkg files. nuget Compares two versions of a package; in a solution, the version diff --git a/tests/assembly-differ.Tests/.snapshots/PullRequestTests/A_pull_request_that_breaks_the_api_fails_and_is_labelled_whatever_the_release_says.verified.txt b/tests/assembly-differ.Tests/.snapshots/PullRequestTests/A_pull_request_that_breaks_the_api_fails_and_is_labelled_whatever_the_release_says.verified.txt new file mode 100644 index 0000000..aaa158f --- /dev/null +++ b/tests/assembly-differ.Tests/.snapshots/PullRequestTests/A_pull_request_that_breaks_the_api_fails_and_is_labelled_whatever_the_release_says.verified.txt @@ -0,0 +1,36 @@ + + +> [!CAUTION] +> This check fails on this change. If it is intended, add the `breaking-allowed` label to allow it. + +### API changes in this pull request: suggested version change **Major** + +Compared with the base branch `2.0/8-base` (#226). ⚠️ 1 breaking change. + +- ✅ **Lib (netstandard2.0)**: no changes + +
Lib (net10.0, net8.0, net462): Major, 1 breaking change + +- 🔴 Lib › Widget › Draw() removed void Draw() [major: breaks callers, compiled code and source] 💥 + +
+ +
Since the last release (`1.1.0`): Major, 32 breaking changes; for information, it does not fail this check + +⚠️ 32 breaking changes. + +
Lib.dll: Major, 32 breaking changes + +- 🔷 type Widget + - 🔴 method `Draw()` 💥 + +
+ +**Introduced by** the pull requests below this one: + +| Pull request | Change | Breaking | +|---|---|---| +| [#220](https://github.com/owner/repo/pull/220) Fix retry budget \| sniffing | Major | 17 | +| [#221](https://github.com/owner/repo/pull/221) Model the pipeline as states | Major | 14 | + +
diff --git a/tests/assembly-differ.Tests/.snapshots/PullRequestTests/A_pull_request_that_changes_nothing_passes_however_much_the_stack_below_it_changed.verified.txt b/tests/assembly-differ.Tests/.snapshots/PullRequestTests/A_pull_request_that_changes_nothing_passes_however_much_the_stack_below_it_changed.verified.txt new file mode 100644 index 0000000..635fa91 --- /dev/null +++ b/tests/assembly-differ.Tests/.snapshots/PullRequestTests/A_pull_request_that_changes_nothing_passes_however_much_the_stack_below_it_changed.verified.txt @@ -0,0 +1,27 @@ + + +### API changes in this pull request: suggested version change **None** + +Compared with the base branch `2.0/8-base` (#226). ✅ All good: this pull request does not change the public API. + +- ✅ **Lib (net10.0, net8.0, net462)**: no changes + +
Since the last release (`1.1.0`): Major, 32 breaking changes; for information, it does not fail this check + +⚠️ 32 breaking changes. + +
Lib.dll: Major, 32 breaking changes + +- 🔷 type Widget + - 🔴 method `Draw()` 💥 + +
+ +**Introduced by** the pull requests below this one: + +| Pull request | Change | Breaking | +|---|---|---| +| [#220](https://github.com/owner/repo/pull/220) Fix retry budget \| sniffing | Major | 17 | +| [#221](https://github.com/owner/repo/pull/221) Model the pipeline as states | Major | 14 | + +
diff --git a/tests/assembly-differ.Tests/ApiDiffTests.cs b/tests/assembly-differ.Tests/ApiDiffTests.cs new file mode 100644 index 0000000..724c7da --- /dev/null +++ b/tests/assembly-differ.Tests/ApiDiffTests.cs @@ -0,0 +1,92 @@ +using AwesomeAssertions; +using Nullean.Snapshots; + +namespace Differ.Tests; + +/// The api-diff command: two directories of committed .api files, compared without building anything. +public class ApiDiffTests +{ + private static async Task<(string Old, string New)> Write(Fixture fixture) + { + var before = Path.Combine(fixture.Root, "base-api"); + var after = Path.Combine(fixture.Root, "head-api"); + (await Cli.RunAsync("api", fixture.OldDirectory, "-o", before)).ExitCode.Should().Be(0); + (await Cli.RunAsync("api", fixture.NewDirectory, "-o", after)).ExitCode.Should().Be(0); + return (before, after); + } + + [Test] + public async Task Says_what_a_removed_method_breaks() + { + using var fixture = Scenarios.Create("method-removed"); + var (before, after) = await Write(fixture); + + var result = await Cli.RunAsync("api-diff", before, after); + + result.ExitCode.Should().Be(0, result.Error); + Report.Of(result, fixture).Should().MatchSnapshot(); + } + + [Test] + public async Task Lists_the_apis_without_changes_too() + { + using var fixture = Scenarios.Create("unchanged"); + var (before, after) = await Write(fixture); + + var result = await Cli.RunAsync("api-diff", before, after); + + result.ExitCode.Should().Be(0, result.Error); + result.Out.Should().Contain("1 API compared, 1 without changes").And.Contain("Suggested version change: None"); + } + + [Test] + public async Task Writes_the_report_the_pull_request_comment_reads() + { + using var fixture = Scenarios.Create("method-removed"); + var (before, after) = await Write(fixture); + var report = Path.Combine(fixture.Root, "delta.json"); + + var result = await Cli.RunAsync("api-diff", before, after, "--format", "json", "--output", report); + + result.ExitCode.Should().Be(0, result.Error); + File.ReadAllText(report).Replace("\r\n", "\n", StringComparison.Ordinal).Should().MatchSnapshot(); + } + + [Test] + public async Task An_api_only_one_side_has_is_added_or_removed() + { + using var fixture = Scenarios.Create("unchanged"); + var (before, after) = await Write(fixture); + File.Move(Path.Combine(after, "Lib.api"), Path.Combine(after, "Other.api")); + + var result = await Cli.RunAsync("api-diff", before, after); + + result.ExitCode.Should().Be(0, result.Error); + result.Out.Should().Contain("Lib: only in").And.Contain("so removed").And.Contain("Other: only in").And.Contain("so added"); + result.Out.Should().Contain("Suggested version change: Major"); + } + + [Test] + public async Task A_missing_directory_has_no_apis_so_everything_is_added() + { + using var fixture = Scenarios.Create("unchanged"); + var (_, after) = await Write(fixture); + + var result = await Cli.RunAsync("api-diff", Path.Combine(fixture.Root, "no-such-directory"), after); + + result.ExitCode.Should().Be(0, result.Error); + result.Out.Should().Contain("Lib: only in").And.Contain("so added").And.Contain("Suggested version change: Minor"); + } + + [Test] + public async Task Json_needs_an_output_file() + { + using var fixture = Scenarios.Create("unchanged"); + var (before, after) = await Write(fixture); + + var result = await Cli.RunAsync("api-diff", before, after, "--format", "json"); + + result.ExitCode.Should().Be(1); + result.Error.Should().Contain("pass --output"); + } +} diff --git a/tests/assembly-differ.Tests/PullRequestTests.cs b/tests/assembly-differ.Tests/PullRequestTests.cs index e4a9654..8c395c3 100644 --- a/tests/assembly-differ.Tests/PullRequestTests.cs +++ b/tests/assembly-differ.Tests/PullRequestTests.cs @@ -330,4 +330,110 @@ public async Task An_API_files_check_that_could_not_run_fails_with_its_own_exit_ result.ExitCode.Should().Be(1, result.Error); github.Comments.Should().ContainSingle().Which.Body.Should().Contain("could not be checked (exit code 1)"); } + + private const string Cumulative = + """ + { + "firstRelease": false, "baseline": "1.1.0", "suggestedVersionChange": "Major", "breakingChanges": 32, + "assemblies": [ + { "name": "Lib.dll", "suggestedVersionChange": "Major", "breakingChanges": 32, + "changes": [ { "kind": "Declaration", "name": "type Widget", "change": "modified", "suggestedVersionChange": "Major", + "changes": [ { "kind": "Method", "name": "Draw()", "change": "removed", "suggestedVersionChange": "Major" } ] } ] } + ], + "removedAssemblies": [], "addedAssemblies": [] + } + """; + + private const string Stack = + """ + [ + { "number": 220, "title": "Fix retry budget | sniffing", "url": "https://github.com/owner/repo/pull/220", "suggestedVersionChange": "Major", "breakingChanges": 17 }, + { "number": 221, "title": "Model the pipeline as states", "url": "https://github.com/owner/repo/pull/221", "suggestedVersionChange": "Major", "breakingChanges": 14 }, + { "number": 222, "title": "Only tests", "url": "https://github.com/owner/repo/pull/222", "suggestedVersionChange": "None", "breakingChanges": 0 } + ] + """; + + private static string Delta(string suggested, int breaking, string frameworks) => + $$""" + { + "firstRelease": false, "suggestedVersionChange": "{{suggested}}", "breakingChanges": {{breaking}}, "distinctBreakingChanges": {{breaking}}, + "assemblies": [ {{frameworks}} ], + "removedAssemblies": [], "addedAssemblies": [] + } + """; + + private static string Framework(string name, string change) => + change.Length == 0 + ? $$"""{ "name": "{{name}}", "suggestedVersionChange": "None", "breakingChanges": 0, "changes": [] }""" + : $$"""{ "name": "{{name}}", "suggestedVersionChange": "Major", "breakingChanges": 1, "changes": [ { "kind": "Declaration", "name": "{{change}}", "change": "removed", "suggestedVersionChange": "Major" } ] }"""; + + private static async Task Reports(Fixture fixture, string delta) + { + var release = Path.Combine(fixture.Root, "release.json"); + var own = Path.Combine(fixture.Root, "delta.json"); + var stack = Path.Combine(fixture.Root, "stack.json"); + await File.WriteAllTextAsync(release, Cumulative); + await File.WriteAllTextAsync(own, delta); + await File.WriteAllTextAsync(stack, Stack); + return [release, "--base-report", own, "--base-name", "`2.0/8-base` (#226)", "--stack", stack]; + } + + [Test] + public async Task A_pull_request_that_changes_nothing_passes_however_much_the_stack_below_it_changed() + { + using var fixture = Scenarios.Create("unchanged"); + using var github = new FakeGitHub(); + var clean = Delta("None", 0, string.Join(", ", new[] { "Lib.net10.0", "Lib.net8.0", "Lib.net462" }.Select(n => Framework(n, "")))); + var arguments = await Reports(fixture, clean); + + var (result, _) = await PullRequest(github, fixture, arguments[0], true, [.. arguments[1..], "--fail-on", "major"]); + + result.ExitCode.Should().Be(0, result.Error); + github.Labels.Should().BeEmpty(); + github.Comments.Should().ContainSingle().Which.Body.Should().MatchSnapshot(); + } + + [Test] + public async Task A_pull_request_that_breaks_the_api_fails_and_is_labelled_whatever_the_release_says() + { + using var fixture = Scenarios.Create("unchanged"); + using var github = new FakeGitHub(); + const string Removed = "Lib › Widget › Draw() removed void Draw() [major: breaks callers, compiled code and source]"; + var delta = Delta( + "Major", + 2, + string.Join( + ", ", + new[] + { + Framework("Lib.net10.0", Removed), + Framework("Lib.net8.0", Removed), + Framework("Lib.net462", Removed), + Framework("Lib.netstandard2.0", ""), + } + ) + ); + var arguments = await Reports(fixture, delta); + + var (result, _) = await PullRequest(github, fixture, arguments[0], true, [.. arguments[1..], "--fail-on", "major"]); + + result.ExitCode.Should().Be(4, result.Error); + github.Labels.Should().Equal("breaking"); + github.Comments.Should().ContainSingle().Which.Body.Should().MatchSnapshot(); + } + + [Test] + public async Task The_allow_label_lets_a_pull_request_through_that_breaks_the_api_itself() + { + using var fixture = Scenarios.Create("unchanged"); + using var github = new FakeGitHub(); + github.Labels.Add("breaking-allowed"); + var delta = Delta("Major", 1, Framework("Lib", "Lib › Widget › Draw() removed void Draw() [major: breaks callers, compiled code and source]")); + var arguments = await Reports(fixture, delta); + + var (result, _) = await PullRequest(github, fixture, arguments[0], true, [.. arguments[1..], "--fail-on", "major"]); + + result.ExitCode.Should().Be(0, result.Error); + github.Comments.Should().ContainSingle().Which.Body.Should().Contain("The `breaking-allowed` label allows this change"); + } }