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
12 changes: 6 additions & 6 deletions .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
10 changes: 10 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project>

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.0.0</Version>
</PropertyGroup>

</Project>
12 changes: 12 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
<NoWarn>$(NoWarn);NU1507</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Microsoft.Build.Tasks.Core" Version="17.12.50" />
<PackageVersion Include="Mono.Cecil" Version="0.11.6" />
<PackageVersion Include="System.Security.Cryptography.Xml" Version="10.0.9" />
</ItemGroup>
</Project>
8 changes: 8 additions & 0 deletions IgnoresAccessChecksToGenerator.slnx
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/IgnoresAccessChecksToGenerator.Tasks/IgnoresAccessChecksToGenerator.Tasks.csproj" />
</Folder>
<Folder Name="/test/">
<Project Path="test/IgnoresAccessChecksToGenerator.Tasks.Test/IgnoresAccessChecksToGenerator.Tasks.Test.csproj" />
</Folder>
</Solution>
65 changes: 56 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,59 @@ Just add the package and define `IgnoresAccessChecksTo` items with the assemblie
</Project>
```

> [!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
> <PropertyGroup>
> <CompileUsingReferenceAssemblies>false</CompileUsingReferenceAssemblies>
> </PropertyGroup>
> ```
### 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
<Project Sdk="Microsoft.NET.Sdk">

<ItemGroup>
<IgnoresAccessChecksTo Include="AssemblyToGrantAccessTo1" />
<IgnoresAccessChecksTo Include="AssemblyToGrantAccessTo2" />

<!-- Excluded from every processed assembly -->
<IgnoresAccessChecksToExcludeTypeName Include="Namespace.TypeName" />

<!-- Excluded only from AssemblyToGrantAccessTo1 -->
<IgnoresAccessChecksToExcludeTypeName Include="Namespace.OtherTypeName" Assembly="AssemblyToGrantAccessTo1" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="IgnoresAccessChecksToGenerator" Version="0.8.0" PrivateAssets="All" />
</ItemGroup>

</Project>
```

### 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
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<IgnoresAccessChecksToOmitAttributeDefinition>true</IgnoresAccessChecksToOmitAttributeDefinition>
</PropertyGroup>

<ItemGroup>
<IgnoresAccessChecksTo Include="AssemblyToGrantAccessTo" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="IgnoresAccessChecksToGenerator" Version="0.8.0" PrivateAssets="All" />
</ItemGroup>

</Project>
```

### 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
<PropertyGroup>
<CompileUsingReferenceAssemblies>false</CompileUsingReferenceAssemblies>
</PropertyGroup>
```
11 changes: 11 additions & 0 deletions global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"sdk": {
"version": "10.0.301"
},
"msbuild-sdks": {
"MSTest.Sdk": "4.2.3"
},
"test": {
"runner": "Microsoft.Testing.Platform"
}
}
3 changes: 2 additions & 1 deletion test/nuget.config → nuget.config
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="LocalFeed" value="../src/IgnoresAccessChecksToGenerator.Tasks/bin/Release/" />
<clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework></TargetFramework>
<TargetFrameworks>netstandard2.0;net462</TargetFrameworks>
<LangVersion>latest</LangVersion>
<PackageId>IgnoresAccessChecksToGenerator</PackageId>
<Version>0.9.0</Version>
<DevelopmentDependency>true</DevelopmentDependency>
<Authors>Eli Arbel</Authors>
<RepositoryUrl>https://github.com/aelij/IgnoresAccessChecksToGenerator</RepositoryUrl>
Expand All @@ -15,20 +14,16 @@
<SuppressDependenciesWhenPacking>true</SuppressDependenciesWhenPacking>
<TargetsForTfmSpecificBuildOutput>$(TargetsForTfmSpecificBuildOutput);IncludePackageDependencies</TargetsForTfmSpecificBuildOutput>
</PropertyGroup>

<ItemGroup>
<Content Include="build\*" PackagePath="build" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Mono.Cecil" Version="0.11.6" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="17.12.50" />
<PackageReference Include="Mono.Cecil" />
<PackageReference Include="Microsoft.Build.Tasks.Core" />
</ItemGroup>

<Target Name="IncludePackageDependencies">
<ItemGroup>
<BuildOutputInPackage Include="@(ReferencePath)" Condition=" '%(Filename)' == 'Mono.Cecil' " />
</ItemGroup>
</Target>

</Project>
</Project>
102 changes: 76 additions & 26 deletions src/IgnoresAccessChecksToGenerator.Tasks/PublicizeInternals.cs
Original file line number Diff line number Diff line change
@@ -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();

Expand All @@ -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));
Expand All @@ -37,16 +39,19 @@ public override bool Execute()
return true;
}

var excludedTypeNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var excludedTypeNames = new TypeExclusions();
if (ExcludeTypeNames != null)
{
excludedTypeNames = new HashSet<string>(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))))
Expand All @@ -62,30 +67,28 @@ 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);
}
}

return true;
}

private void GenerateAttributes(string path, IEnumerable<string> assemblyNames)
private void GenerateAttributes(string path, IEnumerable<string> 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<string> assemblyNames, bool omitAttributeDefinition)
{
var attributes = string.Join(Environment.NewLine,
assemblyNames.Select(a => $@"[assembly: System.Runtime.CompilerServices.IgnoresAccessChecksTo(""{a}"")]"));

var content = $$"""
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

{{attributes}}
var attributeDefinition = omitAttributeDefinition ? "" : """

namespace System.Runtime.CompilerServices
{
Expand All @@ -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 = $$"""
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

{{attributes}}
{{attributeDefinition}}
""";
return content.TrimEnd() + Environment.NewLine;
}

private void CreatePublicAssembly(string source, string target, HashSet<string> 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)
{
Expand Down Expand Up @@ -159,6 +174,41 @@ private void CreatePublicAssembly(string source, string target, HashSet<string>
private string GetFullFilePath(string basePath, string path) =>
Path.IsPathRooted(path) ? Path.GetFullPath(path) : Path.Combine(basePath, path);

internal sealed class TypeExclusions
{
private readonly HashSet<string> _global = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, HashSet<string>> _perAssembly = new Dictionary<string, HashSet<string>>(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<string>(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<string> _directories = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,7 @@

<UsingTask AssemblyFile="$(_IACTG_TaskAssembly)" TaskName="IgnoresAccessChecksToGenerator.Tasks.PublicizeInternals" />

<!--
MSBuild incremental build tracking only supports files, so we create a manifest that contains all the items we use as inputs.
This target has MSBuildAllProjects as input which means it will be invalidated on any project file change.
-->
<Target Name="GetIgnoresAccessChecksToGeneratorReferencePaths"
Inputs="$(MSBuildAllProjects)"
Outputs="$(_IACTG_ManifestFilePath)"
Returns="@(_IACTG_InputReferencePath);@(_IACTG_OutputReferencePath)">
<ItemGroup>
<!-- legacy properties/items -->
Expand All @@ -33,7 +27,8 @@
<_IACTG_OutputReferencePath Include="@(_IACTG_InputReferencePath->'$(_IACTG_IntermediatePath)/%(Filename)%(Extension)')" OriginalItemSpec="%(Identity)" />
</ItemGroup>
<ItemGroup>
<_IACTG_Manifest Include="@(IgnoresAccessChecksToExcludeTypeName)" />
<_IACTG_Manifest Include="@(IgnoresAccessChecksToExcludeTypeName->'%(Identity)^%(Assembly)')" />
<_IACTG_Manifest Include="@(_IACTG_InputReferencePath)" />
</ItemGroup>
<WriteLinesToFile File="$(_IACTG_ManifestFilePath)" Lines="@(_IACTG_Manifest)" WriteOnlyWhenDifferent="true" Overwrite="true" />
</Target>
Expand All @@ -48,7 +43,8 @@
AssemblyNames="@(IgnoresAccessChecksTo)"
ExcludeTypeNames="@(IgnoresAccessChecksToExcludeTypeName)"
IntermediateOutputPath="$(_IACTG_IntermediatePath)"
GeneratedCodeFilePath="$(_IACTG_CodeFilePath)" />
GeneratedCodeFilePath="$(_IACTG_CodeFilePath)"
OmitAttributeDefinition="$(IgnoresAccessChecksToOmitAttributeDefinition)" />
<ItemGroup>
<ReferencePath Include="@(_IACTG_OutputReferencePath)" />
<ReferencePath Remove="@(_IACTG_OutputReferencePath->'%(OriginalItemSpec)')" />
Expand Down
Loading
Loading