diff --git a/README.md b/README.md
index dc6edd5..eb580a1 100644
--- a/README.md
+++ b/README.md
@@ -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
diff --git a/src/assembly-differ/ApiFiles/ApiFileCommand.cs b/src/assembly-differ/ApiFiles/ApiFileCommand.cs
index c2e0a14..4330c8b 100644
--- a/src/assembly-differ/ApiFiles/ApiFileCommand.cs
+++ b/src/assembly-differ/ApiFiles/ApiFileCommand.cs
@@ -37,6 +37,7 @@ internal sealed class ApiFileCommand
/// Read this project file, whatever kind it is. Repeat it for more than one.
/// Read test projects too.
/// Read projects with IsPackable set to false too.
+ /// -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.
/// dotnet build -c Release && assembly-differ api -o api
/// assembly-differ api --verify api
/// assembly-differ api bin/Release/net8.0/MyLib.dll
@@ -52,7 +53,8 @@ public int Api(
string? framework = null,
List? project = null,
bool includeTests = false,
- bool includeUnpackable = false
+ bool includeUnpackable = false,
+ List? reference = null
)
{
var splitting = split switch
@@ -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(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");
@@ -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);
@@ -106,13 +116,19 @@ public int Api(
}
}
- /// An assembly to read, for a framework if it is known.
- internal sealed record Build(string AssemblyName, string? Framework, string Path);
+ /// An assembly to read, for a framework if it is known, and the directories that hold what it refers to.
+ internal sealed record Build(string AssemblyName, string? Framework, string Path, IReadOnlyList References);
/// An assembly's API, for each framework that has it, under the file name it is written to.
internal sealed record Assembly(string FileName, Nullean.PublicApi.ApiAssembly Api);
- private static List Builds(string? path, string? framework, HashSet targets, ProjectComparison.Options options)
+ private static List Builds(
+ string? path,
+ string? framework,
+ HashSet targets,
+ ProjectComparison.Options options,
+ IReadOnlyList references
+ )
{
bool Wanted(string name) => targets.Count == 0 || targets.Contains(name);
@@ -131,12 +147,13 @@ private static List Builds(string? path, string? framework, HashSet 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(
@@ -144,7 +161,9 @@ private static List Builds(string? path, string? framework, HashSet Builds(string? path, string? framework, HashSet 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)];
}
///
@@ -183,7 +202,7 @@ private static List Read(List 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)
@@ -260,6 +279,7 @@ private static string UpdateCommand(
List? project,
bool includeTests,
bool includeUnpackable,
+ List? reference,
string directory
)
{
@@ -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();
}
}
diff --git a/src/assembly-differ/ApiFiles/ProjectAssets.cs b/src/assembly-differ/ApiFiles/ProjectAssets.cs
new file mode 100644
index 0000000..73e0f7a
--- /dev/null
+++ b/src/assembly-differ/ApiFiles/ProjectAssets.cs
@@ -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;
+
+///
+/// The packages a project restored, from its obj/project.assets.json. 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.
+///
+internal static class ProjectAssets
+{
+ ///
+ /// 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.
+ ///
+ public static IReadOnlyList 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();
+ var seen = new HashSet(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;
+ }
+}
diff --git a/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.api.8c1e0300.verified.txt b/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.api.8c1e0300.verified.txt
index eadb94a..52ea0b3 100644
--- a/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.api.8c1e0300.verified.txt
+++ b/tests/assembly-differ.Tests/.snapshots/CommandsTests/Help.api.8c1e0300.verified.txt
@@ -6,18 +6,19 @@ Arguments:
[] 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 Write the files to this directory, and remove the .api files there the API no longer has. [default: null]
- --verify Check that the .api files in this directory match the build, and exit with 5 when they do not. [default: null]
- --split 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 text writes .api files; json prints the API with every part of each declaration as a field. [default: text] [allowed: text|json]
- -t, --target [repeatable] Only these assemblies, by file name without extension. Repeat it for more than one. [default: null]
- --framework Only this target framework, such as net8.0. [default: null]
- --project [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 Write the files to this directory, and remove the .api files there the API no longer has. [default: null]
+ --verify Check that the .api files in this directory match the build, and exit with 5 when they do not. [default: null]
+ --split 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 text writes .api files; json prints the API with every part of each declaration as a field. [default: text] [allowed: text|json]
+ -t, --target [repeatable] Only these assemblies, by file name without extension. Repeat it for more than one. [default: null]
+ --framework Only this target framework, such as net8.0. [default: null]
+ --project [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 [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:
diff --git a/tests/assembly-differ.Tests/ApiReferenceTests.cs b/tests/assembly-differ.Tests/ApiReferenceTests.cs
new file mode 100644
index 0000000..9c230bd
--- /dev/null
+++ b/tests/assembly-differ.Tests/ApiReferenceTests.cs
@@ -0,0 +1,125 @@
+using System.Diagnostics;
+using AwesomeAssertions;
+
+namespace Differ.Tests;
+
+///
+/// An enum default from a package: void Run(Mode mode = Mode.Auto), where Mode 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.
+///
+[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"),
+ $"""
+
+
+ net11.0
+
+
+
+
+
+ """
+ );
+ 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"),
+ $"""
+
+
+
+
+
+
+
+ """
+ );
+ }
+
+ 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 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 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");
+ }
+}