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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,11 @@ directory or a `.nupkg` instead of the solution, `--split namespace` or
`--split top-level-namespace` for a file per namespace in a large assembly, and `-f json` to print every part of each
declaration as a field.

An enum default is written by name, `Formatting formatting = Formatting.Indented`, which needs the assembly that
declares the enum. A project's come from its restore, `obj/project.assets.json`, and the framework's from the
installed runtime. A `.dll` or `.nupkg` read on its own finds only what sits next to it: pass the folders that hold
its dependencies with `-r`, or the value is written as a cast, `(Formatting)1`.

Check them on every pull request with the `verify-api` action. Checkout and the build are your steps, before it:

```yaml
Expand Down
50 changes: 36 additions & 14 deletions src/assembly-differ/ApiFiles/ApiFileCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ internal sealed class ApiFileCommand
/// <param name="project">Read this project file, whatever kind it is. Repeat it for more than one.</param>
/// <param name="includeTests">Read test projects too.</param>
/// <param name="includeUnpackable">Read projects with IsPackable set to false too.</param>
/// <param name="reference">-r, Look in this directory for the assemblies an API refers to, such as a package's dependencies, so an enum default is written by name. Repeat it for more than one. Projects find their packages without it.</param>
/// <example>dotnet build -c Release &amp;&amp; assembly-differ api -o api</example>
/// <example>assembly-differ api --verify api</example>
/// <example>assembly-differ api bin/Release/net8.0/MyLib.dll</example>
Expand All @@ -52,7 +53,8 @@ public int Api(
string? framework = null,
List<string>? project = null,
bool includeTests = false,
bool includeUnpackable = false
bool includeUnpackable = false,
List<string>? reference = null
)
{
var splitting = split switch
Expand All @@ -69,7 +71,10 @@ public int Api(
throw new ArgumentException("pass -o to write the files, or --verify to check them, not both");

var targets = new HashSet<string>(target ?? [], StringComparer.OrdinalIgnoreCase);
var builds = Builds(path, framework, targets, new ProjectComparison.Options(project ?? [], includeTests, includeUnpackable));
var references = (reference ?? []).Select(Path.GetFullPath).ToList();
foreach (var directory in references.Where(d => !Directory.Exists(d)))
throw new DirectoryNotFoundException($"no directory at {directory}, which --reference names");
var builds = Builds(path, framework, targets, new ProjectComparison.Options(project ?? [], includeTests, includeUnpackable), references);
if (builds.Count == 0)
{
Console.Error.WriteLine("[api] no assembly to read");
Expand All @@ -85,7 +90,12 @@ public int Api(

var files = Files(assemblies, splitting);
if (verify is not null)
return Verify.Run(verify, files, assemblies, UpdateCommand(path, split, target, framework, project, includeTests, includeUnpackable, verify));
return Verify.Run(
verify,
files,
assemblies,
UpdateCommand(path, split, target, framework, project, includeTests, includeUnpackable, reference, verify)
);
if (output is not null)
{
Write(output, files);
Expand All @@ -106,13 +116,19 @@ public int Api(
}
}

/// <summary>An assembly to read, for a framework if it is known.</summary>
internal sealed record Build(string AssemblyName, string? Framework, string Path);
/// <summary>An assembly to read, for a framework if it is known, and the directories that hold what it refers to.</summary>
internal sealed record Build(string AssemblyName, string? Framework, string Path, IReadOnlyList<string> References);

/// <summary>An assembly's API, for each framework that has it, under the file name it is written to.</summary>
internal sealed record Assembly(string FileName, Nullean.PublicApi.ApiAssembly Api);

private static List<Build> Builds(string? path, string? framework, HashSet<string> targets, ProjectComparison.Options options)
private static List<Build> Builds(
string? path,
string? framework,
HashSet<string> targets,
ProjectComparison.Options options,
IReadOnlyList<string> references
)
{
bool Wanted(string name) => targets.Count == 0 || targets.Contains(name);

Expand All @@ -131,20 +147,23 @@ private static List<Build> Builds(string? path, string? framework, HashSet<strin
continue;
foreach (var tfm in library.Frameworks.Where(f => chosen is null || f.Equals(chosen)))
{
var targetPath = Dotnet.Properties(
var properties = Dotnet.Properties(
library.Path,
["TargetPath"],
["TargetPath", "ProjectAssetsFile"],
$"TargetFramework={tfm.GetShortFolderName()}",
"Configuration=Release"
)["TargetPath"];
);
var targetPath = properties["TargetPath"];
if (!File.Exists(targetPath))
{
Console.Error.WriteLine(
$"[api] warning: skipping {library.AssemblyName} ({tfm.GetShortFolderName()}), which has no build output at {targetPath}; build it first with: dotnet build -c Release"
);
continue;
}
builds.Add(new Build(library.AssemblyName, tfm.GetShortFolderName(), targetPath));
// the packages restore put in the packages folder, which a library's build output does not copy
var packages = ProjectAssets.Directories(properties.GetValueOrDefault("ProjectAssetsFile"), tfm);
builds.Add(new Build(library.AssemblyName, tfm.GetShortFolderName(), targetPath, [.. references, .. packages]));
}
}
return builds;
Expand All @@ -156,17 +175,17 @@ private static List<Build> Builds(string? path, string? framework, HashSet<strin
return frameworks.SelectMany(
f => new NupkgAssemblyProvider(path, f)
.GetAssemblies(targets)
.Select(a => new Build(System.IO.Path.GetFileNameWithoutExtension(a.Name), f.GetShortFolderName(), a.FullName))
.Select(a => new Build(System.IO.Path.GetFileNameWithoutExtension(a.Name), f.GetShortFolderName(), a.FullName, references))
).ToList();
}
if (Directory.Exists(path))
return new DirectoryAssemblyProvider(path)
.GetAssemblies(targets)
.Select(a => new Build(System.IO.Path.GetFileNameWithoutExtension(a.Name), framework, a.FullName))
.Select(a => new Build(System.IO.Path.GetFileNameWithoutExtension(a.Name), framework, a.FullName, references))
.ToList();
if (!File.Exists(path))
throw new FileNotFoundException($"no .dll, directory or .nupkg at {path}");
return [new Build(System.IO.Path.GetFileNameWithoutExtension(path), framework, path)];
return [new Build(System.IO.Path.GetFileNameWithoutExtension(path), framework, path, references)];
}

/// <summary>
Expand All @@ -183,7 +202,7 @@ private static List<Assembly> Read(List<Build> builds)
{
try
{
var api = Nullean.PublicApi.ApiReader.Read(build.Path);
var api = Nullean.PublicApi.ApiReader.Read(build.Path, new Nullean.PublicApi.ApiReaderOptions { ReferenceDirectories = build.References });
read.Add((build, api, Nullean.PublicApi.ApiWriter.Write(api)));
}
catch (Exception e) when (e is BadImageFormatException or InvalidOperationException)
Expand Down Expand Up @@ -260,6 +279,7 @@ private static string UpdateCommand(
List<string>? project,
bool includeTests,
bool includeUnpackable,
List<string>? reference,
string directory
)
{
Expand All @@ -278,6 +298,8 @@ string directory
command.Append(" --include-tests");
if (includeUnpackable)
command.Append(" --include-unpackable");
foreach (var folder in reference ?? [])
command.Append(" -r ").Append(folder);
return command.Append(" -o ").Append(directory).ToString();
}
}
69 changes: 69 additions & 0 deletions src/assembly-differ/ApiFiles/ProjectAssets.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using NuGet.Frameworks;

namespace Differ.ApiFiles;

/// <summary>
/// The packages a project restored, from its <c>obj/project.assets.json</c>. A library's build output holds only the
/// library, so the assemblies that declare the enums its API uses from a package are found here, where restore put them.
/// </summary>
internal static class ProjectAssets
{
/// <summary>
/// The directories that hold the assemblies a framework compiles against from packages, in the packages folders the
/// file names; empty when the file is missing or says nothing for the framework.
/// </summary>
public static IReadOnlyList<string> Directories(string? assetsFile, NuGetFramework framework)
{
if (assetsFile is null || !File.Exists(assetsFile))
return [];
using var document = JsonDocument.Parse(File.ReadAllBytes(assetsFile));
var root = document.RootElement;
if (!root.TryGetProperty("targets", out var targets) || !root.TryGetProperty("libraries", out var libraries))
return [];

var folders = root.TryGetProperty("packageFolders", out var packageFolders) ? packageFolders.EnumerateObject().Select(f => f.Name).ToList() : [];
if (folders.Count == 0)
return [];

var directories = new List<string>();
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var target in targets.EnumerateObject())
{
// "net8.0", or ".NETCoreApp,Version=v8.0" in older files; "net8.0/linux-x64" is the same compile set for a runtime
if (target.Name.Contains('/') || !NuGetFramework.Parse(target.Name).Equals(framework))
continue;
foreach (var library in target.Value.EnumerateObject())
{
if (
!library.Value.TryGetProperty("type", out var type) || type.GetString() != "package" ||
!library.Value.TryGetProperty("compile", out var compile) || !libraries.TryGetProperty(library.Name, out var entry) ||
!entry.TryGetProperty("path", out var path)
)
continue;
foreach (var asset in compile.EnumerateObject())
{
// _._ marks a framework the package supports with nothing to reference
if (!asset.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
continue;
var relative = Path.GetDirectoryName(Path.Combine(path.GetString()!, asset.Name))!;
foreach (var folder in folders)
{
var directory = Path.GetFullPath(Path.Combine(folder, relative));
if (Directory.Exists(directory) && seen.Add(directory))
{
directories.Add(directory);
break;
}
}
}
}
}
return directories;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,19 @@ Arguments:
[<path>] A .dll, a directory of them, or a .nupkg. Defaults to the libraries in the current directory. [default: null]

Global options:
-h, --help Show help.
-h, --help Show help.

Options:
-o, --output <string> Write the files to this directory, and remove the .api files there the API no longer has. [default: null]
--verify <string> Check that the .api files in this directory match the build, and exit with 5 when they do not. [default: null]
--split <string> Split each API into a file per namespace, or per namespace's first two parts, such as System.Collections, for large assemblies. [default: none] [allowed: none|namespace|top-level-namespace]
-f, --format <string> text writes .api files; json prints the API with every part of each declaration as a field. [default: text] [allowed: text|json]
-t, --target <values> [repeatable] Only these assemblies, by file name without extension. Repeat it for more than one. [default: null]
--framework <string> Only this target framework, such as net8.0. [default: null]
--project <values> [repeatable] Read this project file, whatever kind it is. Repeat it for more than one. [default: null]
--include-tests Read test projects too.
--include-unpackable Read projects with IsPackable set to false too.
-o, --output <string> Write the files to this directory, and remove the .api files there the API no longer has. [default: null]
--verify <string> Check that the .api files in this directory match the build, and exit with 5 when they do not. [default: null]
--split <string> Split each API into a file per namespace, or per namespace's first two parts, such as System.Collections, for large assemblies. [default: none] [allowed: none|namespace|top-level-namespace]
-f, --format <string> text writes .api files; json prints the API with every part of each declaration as a field. [default: text] [allowed: text|json]
-t, --target <values> [repeatable] Only these assemblies, by file name without extension. Repeat it for more than one. [default: null]
--framework <string> Only this target framework, such as net8.0. [default: null]
--project <values> [repeatable] Read this project file, whatever kind it is. Repeat it for more than one. [default: null]
--include-tests Read test projects too.
--include-unpackable Read projects with IsPackable set to false too.
-r, --reference <values> [repeatable] Look in this directory for the assemblies an API refers to, such as a package's dependencies, so an enum default is written by name. Repeat it for more than one. Projects find their packages without it. [default: null]

Notes:

Expand Down
125 changes: 125 additions & 0 deletions tests/assembly-differ.Tests/ApiReferenceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
using System.Diagnostics;
using AwesomeAssertions;

namespace Differ.Tests;

/// <summary>
/// An enum default from a package: <c>void Run(Mode mode = Mode.Auto)</c>, where <c>Mode</c> is in a package on a
/// local feed. A library's build output does not hold its packages, so the value is only written by name when the
/// command finds the package: through the project's restore, or a directory passed with --reference.
/// </summary>
[NotInParallel(nameof(ProjectsTests))]
public class ApiReferenceTests
{
private const string PackageId = "AssemblyDiffer.Tests.Modes";

private sealed class Repository : IDisposable
{
public Repository()
{
Fixture = Fixture.Create("namespace Dep { public enum Mode { Off, On, Auto = 5 } }", "namespace Dep { }", referenceAssemblies: true);
Directory = System.IO.Directory.CreateDirectory(Path.Combine(Fixture.Root, "repo")).FullName;
var feed = System.IO.Directory.CreateDirectory(Path.Combine(Fixture.Root, "feed")).FullName;
CommandsTests.Package(Path.Combine(feed, $"{PackageId}.1.0.0.nupkg"), PackageId, "1.0.0", Fixture.OldAssembly, "net11.0");
File.WriteAllText(
Path.Combine(Directory, "Uses.csproj"),
$"""
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="{PackageId}" Version="1.0.0" />
</ItemGroup>
</Project>
"""
);
File.WriteAllText(
Path.Combine(Directory, "Runner.cs"),
"namespace Uses { public class Runner { public void Run(Dep.Mode mode = Dep.Mode.Auto) { } } }"
);
File.WriteAllText(
Path.Combine(Directory, "NuGet.config"),
$"""
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="local" value="{feed}" />
</packageSources>
</configuration>
"""
);
}

public Fixture Fixture { get; }

public string Directory { get; }

public string Packages => Path.Combine(Fixture.Root, "packages");

public string Assembly => Path.Combine(Directory, "bin", "Release", "net11.0", "Uses.dll");

private Dictionary<string, string> Environment => new() { ["NUGET_PACKAGES"] = Packages, ["MSBUILDDISABLENODEREUSE"] = "1" };

public void Build()
{
var start = new ProcessStartInfo("dotnet", ["build", "-c", "Release", "-v", "q"])
{
WorkingDirectory = Directory,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
foreach (var (name, value) in Environment)
start.Environment[name] = value;
using var process = Process.Start(start)!;
var output = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd();
process.WaitForExit();
process.ExitCode.Should().Be(0, output);
// the build output holds the library alone, as a library's does
File.Exists(Path.Combine(Path.GetDirectoryName(Assembly)!, "Lib.dll")).Should().BeFalse();
}

public async Task<CliResult> Run(params string[] args) => await Cli.RunInAsync(Directory, Environment, args);

public void Dispose() => Fixture.Dispose();
}

[Test]
public async Task A_project_finds_its_packages_enums()
{
using var repository = new Repository();
repository.Build();

var result = await repository.Run("api");

result.ExitCode.Should().Be(0, result.Error);
result.Out.Should().Contain("void Run(Mode mode = Mode.Auto)");
}

[Test]
public async Task An_assembly_finds_them_in_a_reference_directory()
{
using var repository = new Repository();
repository.Build();
var package = Path.Combine(repository.Packages, PackageId.ToLowerInvariant(), "1.0.0", "lib", "net11.0");

var alone = await repository.Run("api", repository.Assembly);
var referenced = await repository.Run("api", repository.Assembly, "-r", package);

alone.Out.Should().Contain("void Run(Mode mode = (Mode)5)");
referenced.ExitCode.Should().Be(0, referenced.Error);
referenced.Out.Should().Contain("void Run(Mode mode = Mode.Auto)");
}

[Test]
public async Task A_missing_reference_directory_is_an_error()
{
using var repository = new Repository();

var result = await repository.Run("api", repository.Fixture.OldAssembly, "-r", Path.Combine(repository.Fixture.Root, "nowhere"));

result.ExitCode.Should().Be(1);
result.Error.Should().Contain("which --reference names");
}
}
Loading