Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# assembly-differ

A .NET tool that diffs the public API of two sets of assemblies and suggests the version change it needs (none,
patch, minor, major). A command per source (`release`, `files`, `nuget`, `github`) picks the two sides; the result is
patch, minor, major). A command per source (`projects`, the default, `release`, `files`, `nuget`) picks the two sides; the result is
written as `markdown`, `xml`, `asciidoc`, `github-comment` or `json`. It is also published as a
distroless container (`ghcr.io/nullean/assembly-differ`) and a GitHub Action (`action.yml`) that runs it.

Expand Down Expand Up @@ -81,7 +81,7 @@ one release label.
is reported as more visible, and nested types are named `.Name`. Changing a report is a change to the CLI contract.

- The CLI surface is the contract `action.yml`, the container and other repositories' builds rely on: the commands
(`release`, `files`, `nuget`, `github`) and their options, and the hidden `diff` with its provider specs and flags.
(`projects`, the default, `release`, `files`, `nuget`, `pull-request`) and their options, and the hidden `diff` with its provider specs and flags.
Removing or renaming any of it is a breaking change. `ApiCommands.cs` holds the commands, `DiffRunner.cs` the
comparison they share with `diff`.
- The build diffs this tool against its own previous release (`generateapichanges`), so a broken diff fails its own CI.
Expand Down
25 changes: 22 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,18 @@ runtime installed.

## Quick start

Compare the package you just packed with its last release on nuget.org, and fail the build on a breaking change:
In a repository, build it, then run the tool without a command. It compares every library project with the latest
release of its package:

```sh
dotnet build -c Release && assembly-differ
```

It reads the one solution in the directory, or else the project files in it, and skips test projects and projects with
`IsPackable` set to `false` (`--include-tests` and `--include-unpackable` compare them, and `--project` picks
projects). It does not build: a project without Release output is skipped with a warning.

Compare the package you just packed with its last release, and fail the build on a breaking change:

```sh
assembly-differ release build/output/MyLib.1.3.0.nupkg --fail-on major
Expand All @@ -77,7 +88,7 @@ earlier release is a first release: there is nothing to compare, so the command
| `release <path>` | a new build, as a `.nupkg`, a `.dll` or a directory, with the release before it; pass `--package` and `--version` unless `<path>` is a `.nupkg` |
| `files <old> <new>` | two local builds, each a `.dll`, a directory of dlls or a `.nupkg` |
| `nuget <id> <old-version> <new-version>` | two published versions, from the NuGet sources your NuGet.config lists |
| `github <owner/repo> <commit> <path> --build <command> --artifacts <path>` | a new build with an older commit, cloned and built with the command you give |
| `projects` | every library project in the directory against its latest release; what runs without a command |

Every command takes the same options:

Expand All @@ -89,6 +100,13 @@ Every command takes the same options:
| `--fail-on` | exit with `4` when the suggested change is at least `patch`, `minor` or `major`; `none` (the default) never fails |
| `--framework` | the target framework to compare, such as `net8.0` (`files`, `nuget` and `release`); defaults to the newest the packages share |

To compare with an older commit, check it out and build it next to your working copy, then compare the two builds:

```sh
git worktree add ../old v1.2.0 && dotnet build ../old -c Release
assembly-differ files ../old/src/MyLib/bin/Release/net8.0 src/MyLib/bin/Release/net8.0
```

A single assembly on each side is compared whatever its file name. With more, assemblies pair by file name, and one
only a side has is printed; it counts as removed or added API when `--target` names it.

Expand Down Expand Up @@ -132,7 +150,8 @@ Without write access, as on a pull request from a fork, it writes the job summar
Before it had a command per source, the tool took two provider specs, and `diff` still does, unchanged, for the builds
that call it: `assembly-differ diff "previous-nuget|MyLib|1.3.0|net8.0" "directory|bin" -t MyLib -p major`. A spec is
`assembly|<path>`, `directory|<path>`, `nuget|<id>|<version>|[tfm]`, `previous-nuget|<id>|<version>|[tfm]` or
`github|<owner/repo>|<commit>|<build command>|<relative output path>`. Its options are `-t`, `-o`, `-f` (default
`github|<owner/repo>|<commit>|<build command>|<relative output path>`; `github` is deprecated in favour of the `git
worktree` recipe above. Its options are `-t`, `-o`, `-f` (default
`xml`), `-p`/`--prevent-change` in place of `--fail-on`, and `-a`/`--allow-empty-previous-nuget`, which succeeds when
`previous-nuget` finds no earlier release.

Expand Down
27 changes: 0 additions & 27 deletions src/assembly-differ/ApiCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using System.Linq;
using Differ.Engine;
using Differ.Providers;
using Differ.Providers.GitHub;
using Differ.Providers.NuGet;
using Differ.Providers.PreviousNuGet;
using NuGet.Frameworks;
Expand Down Expand Up @@ -150,32 +149,6 @@ public int Release(
return 0;
}

/// <summary>Compares a new build with an older commit of a GitHub repository, built with the command you give.</summary>
/// <param name="repository">The repository as owner/name.</param>
/// <param name="commit">The commit, branch or tag to build as the old version.</param>
/// <param name="path">The new build: a .dll or a directory.</param>
/// <param name="build">The command that builds the old commit, run in its checkout.</param>
/// <param name="artifacts">Where the build leaves the assemblies, relative to the checkout.</param>
/// <param name="report">How to report the comparison.</param>
/// <example>assembly-differ github nullean/proc 0.13.0 src/Proc/bin/Release/netstandard2.0 --build "dotnet build -c Release" --artifacts src/Proc/bin/Release/netstandard2.0</example>
[CommandName("github")]
public int GitHub(
[Argument] string repository,
[Argument] string commit,
[Argument] string path,
string build,
string artifacts,
[AsParameters] ReportOptions? report = null
) =>
Run(
() =>
(new DiffSide(
new GitHubAssemblyProviderFactory(new Git(Environment.GetEnvironmentVariable("GIT"))).Create([repository, commit, build, artifacts]),
"github"
), Local(path, null)),
report
);

private static int Run(Func<(DiffSide Old, DiffSide New)> sides, ReportOptions? report) =>
Run(() => (((DiffSide Old, DiffSide New)?)sides()), report, () => null)!.Value;

Expand Down
7 changes: 6 additions & 1 deletion src/assembly-differ/DiffCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ internal sealed class DiffCommands
/// <param name="allowEmptyPreviousNuget">
/// -a, --allow-empty-previous-nuget, Don't fail when no previous nuget package could be found to diff against.
/// </param>
[DefaultCommand]
[CommandName("diff")]
[Hidden]
public int Diff(
Expand Down Expand Up @@ -68,6 +67,12 @@ public int Diff(
if (!string.IsNullOrEmpty(part))
targets.Add(part);

if (first.StartsWith("github|", StringComparison.Ordinal) || second.StartsWith("github|", StringComparison.Ordinal))
Console.Error.WriteLine(
"[diff] warning: the github provider is deprecated. Check out and build the old version yourself, for example with " +
"git worktree add ../old <ref>, then compare the two builds with: assembly-differ files <old> <new>"
);

try
{
var firstProvider = providers.GetProvider(first);
Expand Down
8 changes: 7 additions & 1 deletion src/assembly-differ/Program.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
using Differ;
using Nullean.Argh;

// Before it had commands, the tool took two provider specs at the root, such as "nuget|Proc|0.13.0": route those to
// diff, which still takes them, so the builds that call it that way keep working.
if (args.Length > 0 && args[0].Contains('|'))
args = ["diff", .. args];

var app = new ArghApp();
app.Map<ApiCommands>();
app.Map<Differ.PullRequests.PullRequestCommand>();
app.MapAndRootAlias<DiffCommands>();
app.Map<DiffCommands>();
app.MapAndRootAlias<Differ.Projects.ProjectsCommand>();

return await app.RunAsync(args);
84 changes: 84 additions & 0 deletions src/assembly-differ/Projects/Dotnet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Text.Json;

namespace Differ.Projects;

/// <summary>Runs the .NET SDK: <c>dotnet sln list</c>, <c>dotnet msbuild -getProperty</c> and <c>dotnet build</c>.</summary>
internal static class Dotnet
{
public sealed class SdkException(string message) : Exception(message);

public static (int ExitCode, string Output) Run(params string[] args)
{
var start = new ProcessStartInfo("dotnet")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8,
};
foreach (var arg in args)
start.ArgumentList.Add(arg);
start.Environment["DOTNET_NOLOGO"] = "1";
start.Environment["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1";
try
{
using var process = Process.Start(start)!;
var error = process.StandardError.ReadToEndAsync();
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return (process.ExitCode, output + error.Result);
}
catch (Win32Exception)
{
throw new SdkException("comparing projects needs the .NET SDK on the PATH; dotnet was not found");
}
}

/// <summary>The projects a solution lists, as paths relative to the solution's directory.</summary>
public static IReadOnlyList<string> SolutionProjects(string solution)
{
var (exitCode, output) = Run("sln", solution, "list");
if (exitCode != 0)
throw new SdkException($"dotnet sln {solution} list failed:{Environment.NewLine}{output}");
var projects = new List<string>();
foreach (var line in output.Split('\n', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
if (line.EndsWith("proj", StringComparison.OrdinalIgnoreCase))
projects.Add(line);
return projects;
}

/// <summary>MSBuild properties of a project, evaluated with the global properties given.</summary>
public static Dictionary<string, string> Properties(string project, IEnumerable<string> names, params string[] globalProperties)
{
var args = new List<string> { "msbuild", project, "-nologo" };
foreach (var name in names)
args.Add($"-getProperty:{name}");
foreach (var property in globalProperties)
args.Add($"-p:{property}");
var (exitCode, output) = Run([.. args]);
if (exitCode != 0)
throw new SdkException($"dotnet msbuild could not evaluate {project}:{Environment.NewLine}{output}");

var properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var json = output.Trim();
if (json.StartsWith('{'))
{
using var document = JsonDocument.Parse(json);
foreach (var property in document.RootElement.GetProperty("Properties").EnumerateObject())
properties[property.Name] = property.Value.GetString() ?? "";
}
else
{
// with a single -getProperty, msbuild prints the bare value
foreach (var name in names)
properties[name] = json;
}
return properties;
}
}
158 changes: 158 additions & 0 deletions src/assembly-differ/Projects/ProjectComparison.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Differ.Engine;
using Differ.Providers;
using Differ.Providers.NuGet;
using Differ.Providers.PreviousNuGet;
using NuGet.Frameworks;
using NuGet.Versioning;

namespace Differ.Projects;

/// <summary>A project to compare: its file, package id, assembly name and the framework compared.</summary>
internal sealed record Project(string Path, string PackageId, string AssemblyName, NuGetFramework Framework);

/// <summary>Finds, builds and compares the projects in a directory with their latest releases.</summary>
internal static class ProjectComparison
{
public sealed record Options(IReadOnlyList<string> Projects, bool IncludeTests, bool IncludeUnpackable);

public static int Run(string directory, Options options, ReportOptions report)
{
var candidates = Candidates(directory, options.Projects);
if (candidates.Count == 0)
{
Console.Error.WriteLine($"[diff] no solution or project in {directory}; run a command, or pass --project (see --help)");
return 1;
}

var projects = new List<Project>();
foreach (var path in candidates)
{
var properties = Dotnet.Properties(path, ["IsPackable", "IsTestProject", "PackageId", "AssemblyName", "TargetFramework", "TargetFrameworks"]);
var name = System.IO.Path.GetFileNameWithoutExtension(path);
var explicitlyNamed = options.Projects.Count > 0;
if (!explicitlyNamed && IsTrue(properties["IsTestProject"]) && !options.IncludeTests)
{
Console.WriteLine($"[diff] Skipping {name}: a test project (--include-tests compares it)");
continue;
}
if (!explicitlyNamed && !IsTrue(properties["IsPackable"]) && !options.IncludeUnpackable)
{
Console.WriteLine($"[diff] Skipping {name}: IsPackable is false (--include-unpackable compares it)");
continue;
}
var frameworks = (properties["TargetFrameworks"].Length > 0 ? properties["TargetFrameworks"] : properties["TargetFramework"])
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(NuGetFramework.Parse)
.ToList();
if (frameworks.Count == 0)
{
Console.WriteLine($"[diff] Skipping {name}: it has no target framework");
continue;
}
projects.Add(new Project(path, properties["PackageId"], properties["AssemblyName"], Nupkg.Newest(frameworks)));
}
if (projects.Count == 0)
{
Console.WriteLine("[diff] Nothing to compare");
Console.WriteLine($"[diff] Suggested version change: {SuggestedVersionChange.None}");
return 0;
}

var oldAssemblies = new List<DiffSide>();
var newAssemblies = new List<DiffSide>();
var installer = new Providers.NuGet.NuGet();
foreach (var project in projects)
{
var latest = PreviousRelease.Find(project.PackageId, new NuGetVersion(int.MaxValue, 0, 0));
if (latest is null)
{
Console.WriteLine($"[diff] {project.PackageId} has no release yet: nothing to compare");
continue;
}
var targetPath = Dotnet.Properties(
project.Path,
["TargetPath"],
$"TargetFramework={project.Framework.GetShortFolderName()}",
"Configuration=Release"
)["TargetPath"];
if (!File.Exists(targetPath))
{
Console.Error.WriteLine(
$"[diff] warning: skipping {project.AssemblyName}, which has no build output at {targetPath}; build it first with: dotnet build -c Release"
);
continue;
}
var release = $"{project.PackageId} {latest.ToNormalizedString()}";
var released = new NuGetAssemblyProvider(installer, [project.PackageId, latest.ToNormalizedString(), project.Framework.GetShortFolderName()])
.GetAssemblies(new HashSet<string>(StringComparer.OrdinalIgnoreCase) { project.AssemblyName })
.ToList();
if (released.Count == 0)
{
// a tool package, for one, ships its assembly outside lib/
Console.WriteLine($"[diff] {release} ships no {project.AssemblyName}.dll to compare with");
continue;
}
Console.WriteLine($"[diff] Comparing {project.AssemblyName} ({project.Framework.GetShortFolderName()}) with {release}");
oldAssemblies.Add(new DiffSide(new FixedAssemblyProvider(released), "nuget"));
newAssemblies.Add(new DiffSide(new FixedAssemblyProvider([new FileInfo(targetPath)]), "assembly"));
}
if (oldAssemblies.Count == 0)
{
Console.WriteLine($"[diff] Suggested version change: {SuggestedVersionChange.None}");
return 0;
}

var targets = new HashSet<string>(report.Target ?? projects.Select(p => p.AssemblyName), StringComparer.OrdinalIgnoreCase);
var failOn = Enum.Parse<SuggestedVersionChange>(report.FailOn, ignoreCase: true);
return DiffRunner.Run(
new DiffSide(new CompositeAssemblyProvider(oldAssemblies.Select(s => s.Provider)), "projects"),
new DiffSide(new CompositeAssemblyProvider(newAssemblies.Select(s => s.Provider)), "projects"),
new DiffSettings(targets, report.Format, report.Output, failOn, AllowEmptyPreviousNuget: false)
);
}

private static bool IsTrue(string value) => string.Equals(value, "true", StringComparison.OrdinalIgnoreCase);

/// <summary>
/// The project files to consider: the ones named, or the projects of the one solution in the directory, or the
/// project files in it.
/// </summary>
private static List<string> Candidates(string directory, IReadOnlyList<string> named)
{
if (named.Count > 0)
return named.Select(System.IO.Path.GetFullPath).ToList();

var solutions = Directory.EnumerateFiles(directory, "*.slnx").Concat(Directory.EnumerateFiles(directory, "*.sln")).ToList();
if (solutions.Count > 1)
throw new ArgumentException($"{directory} holds more than one solution; pass --project for the projects to compare");
if (solutions.Count == 1)
{
var solutionDirectory = System.IO.Path.GetDirectoryName(solutions[0])!;
return Dotnet.SolutionProjects(solutions[0]).Select(p => System.IO.Path.GetFullPath(System.IO.Path.Combine(solutionDirectory, p))).ToList();
}
return Directory
.EnumerateFiles(directory, "*.csproj")
.Concat(Directory.EnumerateFiles(directory, "*.fsproj"))
.Concat(Directory.EnumerateFiles(directory, "*.vbproj"))
.ToList();
}
}

/// <summary>Assemblies already found, such as the ones a release was unpacked to.</summary>
internal sealed class FixedAssemblyProvider(IReadOnlyList<FileInfo> assemblies) : IAssemblyProvider
{
public IEnumerable<FileInfo> GetAssemblies(HashSet<string> targets) =>
assemblies.Where(a => targets.Count == 0 || targets.Contains(System.IO.Path.GetFileNameWithoutExtension(a.Name)));
}

/// <summary>The assemblies of several providers together, such as one per project.</summary>
internal sealed class CompositeAssemblyProvider(IEnumerable<IAssemblyProvider> providers) : IAssemblyProvider
{
private readonly List<IAssemblyProvider> _providers = providers.ToList();

public IEnumerable<FileInfo> GetAssemblies(HashSet<string> targets) => _providers.SelectMany(p => p.GetAssemblies(targets)).ToList();
}
Loading
Loading