diff --git a/README.md b/README.md index 3d1cfb3..6b893d2 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,16 @@ You can turn off specific docxml related warnings and errors while defaulting Re Note: To get better results, enable the [`IDE0005`](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0005) unnecessary `using` rule. This avoids the C# compiler seeing a false positive assembly usage from unneeded `using` directives causing it to miss a removable dependency. See also the note for why IDE0005 code analysis rule requires `` property to be enabled. Documentation generation is also required for accuracy of used references detection (based on https://github.com/dotnet/roslyn/issues/66188). +Packages are prevented from being trimmed if they contain build files, as there's no reliable way to determine whether it's safe to do so. You can explicitly ignore specific packages' build files and cause them to be solely judged based on whther the libraries are used by adding the package to the `ReferenceTrimmerIgnorePackageBuildFiles` item on a project level, or in `Directory.Build.props`. + +Example: +```xml + + + +``` +A default set of `ReferenceTrimmerIgnorePackageBuildFiles` items is already included for well-known package, notably various `Microsoft.Extensions.*` packages. + ### C++ (.vcxproj projects) ReferenceTrimmer for C++ is an MSBuild [distributed logger](https://learn.microsoft.com/en-us/visualstudio/msbuild/logging-in-a-multi-processor-environment?view=vs-2022). It writes guidance to the MSBuild stdout stream (not to the MSBuild internal logger at this time) and writes `ReferenceTrimmerUnusedMSVCLibraries.json.log` to the build working directory. diff --git a/src/Package/build/ReferenceTrimmer.props b/src/Package/build/ReferenceTrimmer.props index ab9363b..d7b1e0b 100644 --- a/src/Package/build/ReferenceTrimmer.props +++ b/src/Package/build/ReferenceTrimmer.props @@ -22,4 +22,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Package/build/ReferenceTrimmer.targets b/src/Package/build/ReferenceTrimmer.targets index e9d0e1c..18a6d36 100644 --- a/src/Package/build/ReferenceTrimmer.targets +++ b/src/Package/build/ReferenceTrimmer.targets @@ -41,6 +41,7 @@ RuntimeIdentifier="$(RuntimeIdentifier)" NuGetRestoreTargets="$(NuGetRestoreTargets)" TargetFrameworkDirectories="$(TargetFrameworkDirectory)" + IgnorePackageBuildFiles="@(ReferenceTrimmerIgnorePackageBuildFiles)" NuGetPackageRoot="$(NuGetPackageRoot)" /> diff --git a/src/Tasks/CollectDeclaredReferencesTask.cs b/src/Tasks/CollectDeclaredReferencesTask.cs index 392d3dc..061d725 100644 --- a/src/Tasks/CollectDeclaredReferencesTask.cs +++ b/src/Tasks/CollectDeclaredReferencesTask.cs @@ -40,6 +40,8 @@ public sealed class CollectDeclaredReferencesTask : MSBuildTask public ITaskItem[]? PackageReferences { get; set; } + public ITaskItem[]? IgnorePackageBuildFiles { get; set; } + public string? ProjectAssetsFile { get; set; } public string? TargetFrameworkMoniker { get; set; } @@ -170,7 +172,6 @@ public override bool Execute() continue; } - // Ignore packages with build logic as we cannot easily evaluate whether the build logic is necessary or not. if (packageInfo.BuildFiles.Count > 0) { continue; @@ -245,6 +246,12 @@ private Dictionary GetPackageInfos() } } + HashSet packageToIgnoreBuildFiles = new(StringComparer.OrdinalIgnoreCase); + foreach (ITaskItem item in IgnorePackageBuildFiles ?? []) + { + packageToIgnoreBuildFiles.Add(item.ItemSpec); + } + // Get the transitive closure of assemblies included by each package foreach (LockFileTargetLibrary nugetLibrary in nugetLibraries) { @@ -274,11 +281,13 @@ private Dictionary GetPackageInfos() }) .ToList(); - List buildFiles = nugetLibrary.Build - .Select(item => item.Path) - .Where(IsValidFile) - .Select(path => Path.Combine(nugetLibraryAbsolutePath, path)) - .ToList(); + List buildFiles = packageToIgnoreBuildFiles.Contains(nugetLibrary.Name) + ? [] + : nugetLibrary.Build + .Select(item => item.Path) + .Where(IsValidFile) + .Select(path => Path.Combine(nugetLibraryAbsolutePath, path)) + .ToList(); // Add this package's assets, if there are any if (nugetLibraryAssemblies.Count > 0 || buildFiles.Count > 0) diff --git a/src/Tests/E2ETests.cs b/src/Tests/E2ETests.cs index 8f46b66..38e52da 100644 --- a/src/Tests/E2ETests.cs +++ b/src/Tests/E2ETests.cs @@ -491,6 +491,29 @@ public Task PackageReferenceWithFakeBuildFile() ]); } + [TestMethod] + public async Task IgnorePackageBuildFiles() + { + await RunMSBuildAsync( + projectFile: "Library/Library.csproj", + expectedWarnings: [], + globalProperties: new Dictionary + { + { "IgnorePackageBuildFiles", "false" }, + }); + + await RunMSBuildAsync( + projectFile: "Library/Library.csproj", + expectedWarnings: + [ + new Warning("RT0003: PackageReference Microsoft.Extensions.Logging can be removed", "Library/Library.csproj"), + ], + globalProperties: new Dictionary + { + { "IgnorePackageBuildFiles", "true" }, + }); + } + private static (string ExePath, string Verb, string? VsInstallDir) GetMsBuildExeAndVerb() { // On Windows, try to find Visual Studio using vswhere @@ -614,7 +637,13 @@ private static (string ExePath, string Verb, string? VsInstallDir) GetMsBuildExe return env; } - private async Task RunMSBuildAsync(string projectFile, Warning[] expectedWarnings, string[]? expectedConsoleOutputs = null, bool expectUnusedMsvcLibrariesLog = false, bool enableReferenceTrimmerDiagnostics = false) + private async Task RunMSBuildAsync( + string projectFile, + Warning[] expectedWarnings, + string[]? expectedConsoleOutputs = null, + bool expectUnusedMsvcLibrariesLog = false, + bool enableReferenceTrimmerDiagnostics = false, + IReadOnlyDictionary? globalProperties = null) { var testDataSourcePath = Path.GetFullPath(Path.Combine("TestData", TestContext?.TestName ?? string.Empty)); @@ -641,6 +670,14 @@ private async Task RunMSBuildAsync(string projectFile, Warning[] expectedWarning $"-distributedlogger:CentralLogger,\"{loggersAssemblyPath}\"*ForwardingLogger,\"{loggersAssemblyPath}\" " + (enableReferenceTrimmerDiagnostics ? "-p:EnableReferenceTrimmerDiagnostics=true" : string.Empty); + if (globalProperties is not null) + { + foreach ((string key, string value) in globalProperties) + { + msbuildArgs += $" -p:{key}={value}"; + } + } + Process? process = Process.Start( new ProcessStartInfo { diff --git a/src/Tests/TestData/IgnorePackageBuildFiles/Library/Library.cs b/src/Tests/TestData/IgnorePackageBuildFiles/Library/Library.cs new file mode 100644 index 0000000..958c389 --- /dev/null +++ b/src/Tests/TestData/IgnorePackageBuildFiles/Library/Library.cs @@ -0,0 +1,7 @@ +namespace Library +{ + public static class Foo + { + public static string Bar() => "Baz"; + } +} diff --git a/src/Tests/TestData/IgnorePackageBuildFiles/Library/Library.csproj b/src/Tests/TestData/IgnorePackageBuildFiles/Library/Library.csproj new file mode 100644 index 0000000..bc99305 --- /dev/null +++ b/src/Tests/TestData/IgnorePackageBuildFiles/Library/Library.csproj @@ -0,0 +1,23 @@ + + + + Library + net8.0 + + + + + + + + + + + + + + + + + + diff --git a/version.json b/version.json index 02ee64e..a48c5f6 100644 --- a/version.json +++ b/version.json @@ -1,7 +1,7 @@ { "$schema": "https://raw.githubusercontent.com/AArnott/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", - "version": "3.3", - "assemblyVersion": "3.3", + "version": "3.4", + "assemblyVersion": "3.4", "buildNumberOffset": -1, "publicReleaseRefSpec": [ "^refs/tags/v\\d+\\.\\d+\\.\\d+"