diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index dbc6384..2d3f9fc 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -12,12 +12,12 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Setup .NET - uses: actions/setup-dotnet@v1 - with: - dotnet-version: 8.0.x + uses: actions/setup-dotnet@v4 - name: Restore dependencies - run: dotnet restore src + run: dotnet restore - name: Build - run: dotnet build src --no-restore + run: dotnet build --no-restore + - name: Test + run: dotnet test --no-build diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..97b7b08 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,10 @@ + + + + net10.0 + enable + enable + 1.0.0 + + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..372e07c --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,12 @@ + + + true + true + $(NoWarn);NU1507 + + + + + + + \ No newline at end of file diff --git a/IgnoresAccessChecksToGenerator.slnx b/IgnoresAccessChecksToGenerator.slnx new file mode 100644 index 0000000..d71693e --- /dev/null +++ b/IgnoresAccessChecksToGenerator.slnx @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/README.md b/README.md index ed7b42e..0d245ea 100644 --- a/README.md +++ b/README.md @@ -26,12 +26,59 @@ Just add the package and define `IgnoresAccessChecksTo` items with the assemblie ``` -> [!Tip] -> -> If you want to ignore access checks to an assembly coming from a `ProjectReference` instead of a `PackageReference`, you'll need to set the `CompileUsingReferenceAssemblies` property to `false`. -> -> ```xml -> -> false -> -> ``` +### Excluding types + +Use `IgnoresAccessChecksToExcludeTypeName` to keep specific types from being publicized. By default an exclusion applies to every assembly being processed. To scope an exclusion to a single assembly, add the `Assembly` metadata: + +```xml + + + + + + + + + + + + + + + + + + +``` + +### Omitting the attribute definition + +When set to `true`, the generator will not emit the `IgnoresAccessChecksToAttribute` class definition in the generated file. This is useful when you already have the attribute defined elsewhere in your project (for example, when multiple packages use the same attribute). + +```xml + + + + true + + + + + + + + + + + +``` + +### Using with project references + +If you want to ignore access checks to an assembly coming from a `ProjectReference` instead of a `PackageReference`, you'll need to set the `CompileUsingReferenceAssemblies` property to `false`. + +```xml + + false + +``` diff --git a/global.json b/global.json new file mode 100644 index 0000000..c0fa68d --- /dev/null +++ b/global.json @@ -0,0 +1,11 @@ +{ + "sdk": { + "version": "10.0.301" + }, + "msbuild-sdks": { + "MSTest.Sdk": "4.2.3" + }, + "test": { + "runner": "Microsoft.Testing.Platform" + } +} diff --git a/test/nuget.config b/nuget.config similarity index 54% rename from test/nuget.config rename to nuget.config index 80c0a50..de291b7 100644 --- a/test/nuget.config +++ b/nuget.config @@ -1,6 +1,7 @@ - + + diff --git a/src/IgnoresAccessChecksToGenerator.Tasks/IgnoresAccessChecksToGenerator.Tasks.csproj b/src/IgnoresAccessChecksToGenerator.Tasks/IgnoresAccessChecksToGenerator.Tasks.csproj index cc1308f..ec89365 100644 --- a/src/IgnoresAccessChecksToGenerator.Tasks/IgnoresAccessChecksToGenerator.Tasks.csproj +++ b/src/IgnoresAccessChecksToGenerator.Tasks/IgnoresAccessChecksToGenerator.Tasks.csproj @@ -1,10 +1,9 @@  - + netstandard2.0;net462 latest IgnoresAccessChecksToGenerator - 0.9.0 true Eli Arbel https://github.com/aelij/IgnoresAccessChecksToGenerator @@ -15,20 +14,16 @@ true $(TargetsForTfmSpecificBuildOutput);IncludePackageDependencies - - - - + + - - - + \ No newline at end of file diff --git a/src/IgnoresAccessChecksToGenerator.Tasks/PublicizeInternals.cs b/src/IgnoresAccessChecksToGenerator.Tasks/PublicizeInternals.cs index f74e70b..34f7995 100644 --- a/src/IgnoresAccessChecksToGenerator.Tasks/PublicizeInternals.cs +++ b/src/IgnoresAccessChecksToGenerator.Tasks/PublicizeInternals.cs @@ -1,14 +1,14 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; +using System.Runtime.CompilerServices; using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; using Mono.Cecil; +[assembly: InternalsVisibleTo("IgnoresAccessChecksToGenerator.Tasks.Test")] + +#nullable disable + namespace IgnoresAccessChecksToGenerator.Tasks { - public class PublicizeInternals : Task + public class PublicizeInternals : Microsoft.Build.Utilities.Task { private readonly AssemblyResolver _resolver = new AssemblyResolver(); @@ -26,6 +26,8 @@ public class PublicizeInternals : Task public ITaskItem[] ExcludeTypeNames { get; set; } + public bool OmitAttributeDefinition { get; set; } + public override bool Execute() { if (SourceReferences == null) throw new ArgumentNullException(nameof(SourceReferences)); @@ -37,16 +39,19 @@ public override bool Execute() return true; } - var excludedTypeNames = new HashSet(StringComparer.OrdinalIgnoreCase); + var excludedTypeNames = new TypeExclusions(); if (ExcludeTypeNames != null) { - excludedTypeNames = new HashSet(ExcludeTypeNames.Select(t => t.ItemSpec), StringComparer.OrdinalIgnoreCase); + foreach (var item in ExcludeTypeNames) + { + excludedTypeNames.Add(item.ItemSpec, item.GetMetadata("Assembly")); + } } var targetPath = IntermediateOutputPath; Directory.CreateDirectory(targetPath); - GenerateAttributes(targetPath, assemblyNames); + GenerateAttributes(targetPath, assemblyNames, OmitAttributeDefinition); foreach (var assemblyPath in SourceReferences .Select(a => Path.GetDirectoryName(GetFullFilePath(targetPath, a.ItemSpec)))) @@ -62,7 +67,7 @@ public override bool Execute() { var targetAssemblyPath = Path.Combine(targetPath, Path.GetFileName(assemblyPath)); - CreatePublicAssembly(assemblyPath, targetAssemblyPath, excludedTypeNames); + CreatePublicAssembly(assemblyName, assemblyPath, targetAssemblyPath, excludedTypeNames); Log.LogMessageFromText("Created publicized assembly at " + targetAssemblyPath, MessageImportance.Normal); } } @@ -70,22 +75,20 @@ public override bool Execute() return true; } - private void GenerateAttributes(string path, IEnumerable assemblyNames) + private void GenerateAttributes(string path, IEnumerable assemblyNames, bool omitAttributeDefinition) + { + var content = BuildAttributeFileContent(assemblyNames, omitAttributeDefinition); + File.WriteAllText(GeneratedCodeFilePath, content, System.Text.Encoding.UTF8); + + Log.LogMessageFromText("Generated IgnoresAccessChecksTo attributes", MessageImportance.Low); + } + + internal static string BuildAttributeFileContent(IEnumerable assemblyNames, bool omitAttributeDefinition) { var attributes = string.Join(Environment.NewLine, assemblyNames.Select(a => $@"[assembly: System.Runtime.CompilerServices.IgnoresAccessChecksTo(""{a}"")]")); - var content = $$""" -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -{{attributes}} + var attributeDefinition = omitAttributeDefinition ? "" : """ namespace System.Runtime.CompilerServices { @@ -98,19 +101,31 @@ public IgnoresAccessChecksToAttribute(string assemblyName) } } """; - File.WriteAllText(GeneratedCodeFilePath, content, System.Text.Encoding.UTF8); - Log.LogMessageFromText("Generated IgnoresAccessChecksTo attributes", MessageImportance.Low); + var content = $$""" +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +{{attributes}} +{{attributeDefinition}} +"""; + return content.TrimEnd() + Environment.NewLine; } - private void CreatePublicAssembly(string source, string target, HashSet excludedTypeNames) + private void CreatePublicAssembly(string assemblyName, string source, string target, TypeExclusions excludedTypeNames) { var assembly = AssemblyDefinition.ReadAssembly(source, new ReaderParameters { AssemblyResolver = _resolver }); foreach (var module in assembly.Modules) { - foreach (var type in module.GetTypes().Where(type => !excludedTypeNames.Contains(type.FullName))) + foreach (var type in module.GetTypes().Where(type => !excludedTypeNames.IsExcluded(assemblyName, type.FullName))) { if (!type.IsNested && type.IsNotPublic) { @@ -159,6 +174,41 @@ private void CreatePublicAssembly(string source, string target, HashSet private string GetFullFilePath(string basePath, string path) => Path.IsPathRooted(path) ? Path.GetFullPath(path) : Path.Combine(basePath, path); + internal sealed class TypeExclusions + { + private readonly HashSet _global = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary> _perAssembly = new Dictionary>(StringComparer.OrdinalIgnoreCase); + + public void Add(string typeName, string assemblyName) + { + if (string.IsNullOrEmpty(typeName)) + { + return; + } + + if (string.IsNullOrEmpty(assemblyName)) + { + _global.Add(typeName); + } + else + { + if (!_perAssembly.TryGetValue(assemblyName, out var set)) + { + set = new HashSet(StringComparer.OrdinalIgnoreCase); + _perAssembly[assemblyName] = set; + } + + set.Add(typeName); + } + } + + public bool IsExcluded(string assemblyName, string typeFullName) + { + return _global.Contains(typeFullName) || + (_perAssembly.TryGetValue(assemblyName, out var set) && set.Contains(typeFullName)); + } + } + private class AssemblyResolver : IAssemblyResolver { private readonly HashSet _directories = new HashSet(StringComparer.OrdinalIgnoreCase); diff --git a/src/IgnoresAccessChecksToGenerator.Tasks/build/IgnoresAccessChecksToGenerator.targets b/src/IgnoresAccessChecksToGenerator.Tasks/build/IgnoresAccessChecksToGenerator.targets index c53d664..48bb792 100644 --- a/src/IgnoresAccessChecksToGenerator.Tasks/build/IgnoresAccessChecksToGenerator.targets +++ b/src/IgnoresAccessChecksToGenerator.Tasks/build/IgnoresAccessChecksToGenerator.targets @@ -11,13 +11,7 @@ - @@ -33,7 +27,8 @@ <_IACTG_OutputReferencePath Include="@(_IACTG_InputReferencePath->'$(_IACTG_IntermediatePath)/%(Filename)%(Extension)')" OriginalItemSpec="%(Identity)" /> - <_IACTG_Manifest Include="@(IgnoresAccessChecksToExcludeTypeName)" /> + <_IACTG_Manifest Include="@(IgnoresAccessChecksToExcludeTypeName->'%(Identity)^%(Assembly)')" /> + <_IACTG_Manifest Include="@(_IACTG_InputReferencePath)" /> @@ -48,7 +43,8 @@ AssemblyNames="@(IgnoresAccessChecksTo)" ExcludeTypeNames="@(IgnoresAccessChecksToExcludeTypeName)" IntermediateOutputPath="$(_IACTG_IntermediatePath)" - GeneratedCodeFilePath="$(_IACTG_CodeFilePath)" /> + GeneratedCodeFilePath="$(_IACTG_CodeFilePath)" + OmitAttributeDefinition="$(IgnoresAccessChecksToOmitAttributeDefinition)" /> diff --git a/src/IgnoresAccessChecksToGenerator.sln b/src/IgnoresAccessChecksToGenerator.sln deleted file mode 100644 index fd74240..0000000 --- a/src/IgnoresAccessChecksToGenerator.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.5.33103.201 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IgnoresAccessChecksToGenerator.Tasks", "IgnoresAccessChecksToGenerator.Tasks\IgnoresAccessChecksToGenerator.Tasks.csproj", "{FFFAEEE5-E216-442C-9162-168AD30F57F5}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{D43D3D13-84B1-4D21-8E36-52BED4056097}" - ProjectSection(SolutionItems) = preProject - Build\IgnoresAccessChecksToGenerator.props = Build\IgnoresAccessChecksToGenerator.props - Build\IgnoresAccessChecksToGenerator.targets = Build\IgnoresAccessChecksToGenerator.targets - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {FFFAEEE5-E216-442C-9162-168AD30F57F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FFFAEEE5-E216-442C-9162-168AD30F57F5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FFFAEEE5-E216-442C-9162-168AD30F57F5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FFFAEEE5-E216-442C-9162-168AD30F57F5}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {93618651-EC7C-40FD-9683-C87FEC4A4947} - EndGlobalSection -EndGlobal diff --git a/test/IgnoresAccessChecksToGenerator.Tasks.Test/IgnoresAccessChecksToGenerator.Tasks.Test.csproj b/test/IgnoresAccessChecksToGenerator.Tasks.Test/IgnoresAccessChecksToGenerator.Tasks.Test.csproj new file mode 100644 index 0000000..c71b797 --- /dev/null +++ b/test/IgnoresAccessChecksToGenerator.Tasks.Test/IgnoresAccessChecksToGenerator.Tasks.Test.csproj @@ -0,0 +1,7 @@ + + + + + + + diff --git a/test/IgnoresAccessChecksToGenerator.Tasks.Test/PublicizeInternalsTests.cs b/test/IgnoresAccessChecksToGenerator.Tasks.Test/PublicizeInternalsTests.cs new file mode 100644 index 0000000..93e63bf --- /dev/null +++ b/test/IgnoresAccessChecksToGenerator.Tasks.Test/PublicizeInternalsTests.cs @@ -0,0 +1,96 @@ +using IgnoresAccessChecksToGenerator.Tasks; + +namespace IgnoresAccessChecksToGenerator.Tasks.Test; + +[TestClass] +public class PublicizeInternalsTests +{ + [TestMethod] + public void BuildAttributeFileContent_DefaultBehavior_EmitsAttributeDefinition() + { + var content = PublicizeInternals.BuildAttributeFileContent(["TestAssembly"], omitAttributeDefinition: false); + + StringAssert.Contains(content, "class IgnoresAccessChecksToAttribute"); + StringAssert.Contains(content, "[assembly: System.Runtime.CompilerServices.IgnoresAccessChecksTo(\"TestAssembly\")]"); + } + + [TestMethod] + public void BuildAttributeFileContent_OmitAttributeDefinition_DoesNotEmitAttributeClass() + { + var content = PublicizeInternals.BuildAttributeFileContent(["TestAssembly"], omitAttributeDefinition: true); + + Assert.IsFalse(content.Contains("class IgnoresAccessChecksToAttribute")); + StringAssert.Contains(content, "[assembly: System.Runtime.CompilerServices.IgnoresAccessChecksTo(\"TestAssembly\")]"); + } + + [TestMethod] + public void BuildAttributeFileContent_MultipleAssemblies_EmitsAllAssemblyAttributes() + { + var content = PublicizeInternals.BuildAttributeFileContent(["Assembly1", "Assembly2"], omitAttributeDefinition: false); + + StringAssert.Contains(content, "[assembly: System.Runtime.CompilerServices.IgnoresAccessChecksTo(\"Assembly1\")]"); + StringAssert.Contains(content, "[assembly: System.Runtime.CompilerServices.IgnoresAccessChecksTo(\"Assembly2\")]"); + StringAssert.Contains(content, "class IgnoresAccessChecksToAttribute"); + } + + [TestMethod] + public void BuildAttributeFileContent_MultipleAssembliesOmitDefinition_EmitsAllAssemblyAttributesWithoutClass() + { + var content = PublicizeInternals.BuildAttributeFileContent(["Assembly1", "Assembly2"], omitAttributeDefinition: true); + + StringAssert.Contains(content, "[assembly: System.Runtime.CompilerServices.IgnoresAccessChecksTo(\"Assembly1\")]"); + StringAssert.Contains(content, "[assembly: System.Runtime.CompilerServices.IgnoresAccessChecksTo(\"Assembly2\")]"); + Assert.IsFalse(content.Contains("class IgnoresAccessChecksToAttribute")); + } +} + +[TestClass] +public class TypeExclusionsTests +{ + [TestMethod] + public void GlobalExclusion_AppliesToAllAssemblies() + { + var exclusions = new PublicizeInternals.TypeExclusions(); + exclusions.Add("Namespace.TypeName", assemblyName: ""); + + Assert.IsTrue(exclusions.IsExcluded("AssemblyA", "Namespace.TypeName")); + Assert.IsTrue(exclusions.IsExcluded("AssemblyB", "Namespace.TypeName")); + } + + [TestMethod] + public void AssemblyScopedExclusion_AppliesOnlyToThatAssembly() + { + var exclusions = new PublicizeInternals.TypeExclusions(); + exclusions.Add("Namespace.TypeName", assemblyName: "AssemblyA"); + + Assert.IsTrue(exclusions.IsExcluded("AssemblyA", "Namespace.TypeName")); + Assert.IsFalse(exclusions.IsExcluded("AssemblyB", "Namespace.TypeName")); + } + + [TestMethod] + public void AssemblyScopedExclusion_IsCaseInsensitive() + { + var exclusions = new PublicizeInternals.TypeExclusions(); + exclusions.Add("Namespace.TypeName", assemblyName: "AssemblyA"); + + Assert.IsTrue(exclusions.IsExcluded("assemblya", "namespace.typename")); + } + + [TestMethod] + public void UnknownType_IsNotExcluded() + { + var exclusions = new PublicizeInternals.TypeExclusions(); + exclusions.Add("Namespace.TypeName", assemblyName: "AssemblyA"); + + Assert.IsFalse(exclusions.IsExcluded("AssemblyA", "Namespace.OtherType")); + } + + [TestMethod] + public void EmptyTypeName_IsIgnored() + { + var exclusions = new PublicizeInternals.TypeExclusions(); + exclusions.Add("", assemblyName: "AssemblyA"); + + Assert.IsFalse(exclusions.IsExcluded("AssemblyA", "")); + } +} diff --git a/test/IgnoresAccessChecksToGenerator.Test/IgnoresAccessChecksToGenerator.Test.csproj b/test/IgnoresAccessChecksToGenerator.Test/IgnoresAccessChecksToGenerator.Test.csproj index b20dfb1..24e975d 100644 --- a/test/IgnoresAccessChecksToGenerator.Test/IgnoresAccessChecksToGenerator.Test.csproj +++ b/test/IgnoresAccessChecksToGenerator.Test/IgnoresAccessChecksToGenerator.Test.csproj @@ -1,7 +1,6 @@  - net8.0 Exe @@ -12,8 +11,8 @@ - - + + diff --git a/test/IgnoresAccessChecksToGenerator.Test/IgnoresAccessChecksToGenerator.Test.sln b/test/IgnoresAccessChecksToGenerator.Test/IgnoresAccessChecksToGenerator.Test.sln deleted file mode 100644 index b9b2090..0000000 --- a/test/IgnoresAccessChecksToGenerator.Test/IgnoresAccessChecksToGenerator.Test.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26430.16 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IgnoresAccessChecksToGenerator.Test", "IgnoresAccessChecksToGenerator.Test.csproj", "{9BA0FB27-1DAF-43CD-A0EE-F952EE198D5F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9BA0FB27-1DAF-43CD-A0EE-F952EE198D5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9BA0FB27-1DAF-43CD-A0EE-F952EE198D5F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9BA0FB27-1DAF-43CD-A0EE-F952EE198D5F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9BA0FB27-1DAF-43CD-A0EE-F952EE198D5F}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/test/IgnoresAccessChecksToGenerator.Test/nuget.config b/test/IgnoresAccessChecksToGenerator.Test/nuget.config new file mode 100644 index 0000000..5a846b6 --- /dev/null +++ b/test/IgnoresAccessChecksToGenerator.Test/nuget.config @@ -0,0 +1,7 @@ + + + + + + +