Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Skip configuration field check when ConfigurationPath is set #15

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
8 changes: 8 additions & 0 deletions sample/Sample.Components/TestConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Sample.Components;

public class TestConfig
{
public TimeSpan? TimeSpan { get; set; }

public bool? Boolean { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace TestWebApiGenerator;

internal static partial class ServiceRegistrationExtensions
{
[GenerateConfiguration("Services", ExcludedSections = new[] { "Hsts" }, ImplicitSuffixes = new[] { "Instrumentation", "Exporter" }, ConfigurationPath = nameof(WebApplicationBuilder.Configuration))]
[GenerateConfiguration("Services", ExcludedSections = new[] { "Hsts" }, ImplicitSuffixes = new[] { "Instrumentation", "Exporter" }, ConfigurationPath = nameof(WebApplicationBuilder.Configuration), ExpandableSections = new[] { "Extra" })]
public static partial void AddServicesFromConfiguration(this WebApplicationBuilder builder);

// [GenerateServiceRegistration("Services")]
Expand Down
3 changes: 2 additions & 1 deletion sample/TestWebApiGenerator/TestWebApiGenerator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@

<ItemGroup>
<ProjectReference Include="..\..\src\ConfigurationProcessor.Generator\ConfigurationProcessor.Generator.csproj" />
<ProjectReference Include="..\..\src\ConfigurationProcessor.SourceGeneration\ConfigurationProcessor.SourceGeneration.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\..\src\ConfigurationProcessor.SourceGeneration\ConfigurationProcessor.SourceGeneration.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PackAsAnalyzer="true" />
<ProjectReference Include="..\Sample.Components\Sample.Components.csproj" />
</ItemGroup>

</Project>
64 changes: 35 additions & 29 deletions sample/TestWebApiGenerator/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,33 +1,39 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Services": {
"Logging": true,
"Hsts": {
"ExcludedHosts": {
"Clear": true
},
"Preload": true,
"IncludeSubDomains": true,
"MaxAge": "356.00:00:00"
},
"Configure<Microsoft.AspNetCore.Builder.CookiePolicyOptions>": {
"HttpOnly": "Always",
"Secure": "Always"
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Services": {
"Logging": true,
"Hsts": {
"ExcludedHosts": {
"Clear": true
},
"Controllers": true,
"EndpointsApiExplorer": true,
"SwaggerGen": true,
"OpenTelemetryTracing": {
"AspNetCore": true,
"HttpClient": true,
"SqlClient": true,
"Jaeger": true
"Preload": true,
"IncludeSubDomains": true,
"MaxAge": "356.00:00:00"
},
"Extra": {
"Configure<Sample.Components.TestConfig>": {
"TimeSpan": "01:01:01",
"Boolean": true
}
}
},
"Configure<Microsoft.AspNetCore.Builder.CookiePolicyOptions>": {
"HttpOnly": "Always",
"Secure": "Always"
},
"Controllers": true,
"EndpointsApiExplorer": true,
"SwaggerGen": true,
"OpenTelemetryTracing": {
"AspNetCore": true,
"HttpClient": true,
"SqlClient": true,
"Jaeger": true
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="6.0.0" />
<PackageReference Include="System.Reflection.Emit" Version="4.7.0" />
<PackageReference Include="System.Reflection.Emit" Version="4.7.0" />
</ItemGroup>

</Project>
47 changes: 42 additions & 5 deletions src/ConfigurationProcessor.Core/Implementation/CommonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ static bool IsDefined(MethodInfo method, Type attributeType)
{
return candidateMethods
.Where(m => m.IsGenericMethod && CanMakeGeneric(m))
.Select(m => m.MakeGenericMethod(typeArgs.Select((t, i) => t(m, i)).ToArray()))
.Select(m => m.MakeGenericMethod(typeArgs.Select((t, i) => t(m, i)).ToArray().ReplaceFakeTypes(m)))
.ToList();
}

Expand All @@ -194,7 +194,8 @@ bool CanMakeGeneric(MethodInfo method)
{
try
{
method.MakeGenericMethod(typeArgs.Select((t, i) => t(method, i)).ToArray());
var types = typeArgs.Select((t, i) => t(method, i)).ToArray().ReplaceFakeTypes(method);
method.MakeGenericMethod(types);
return true;
}
catch (ArgumentException)
Expand All @@ -221,6 +222,24 @@ static ParameterInfo[] SafeGetParameters(MethodInfo method)
}
}

#pragma warning disable S1172 // Unused method parameters should be removed
private static Type[] ReplaceFakeTypes(this Type[] types, MethodInfo method)
#pragma warning restore S1172 // Unused method parameters should be removed
{
#if Generator
var defaultReplacementType = method.DeclaringType.BaseType;
for (var i = 0; i < types.Length; i++)
{
if (types[i] is SourceGeneration.Utility.FakeType ft)
{
types[i] = ft.BaseType ?? defaultReplacementType;
}
}

#endif
return types;
}

internal static ILookup<string, ConfigLookup> GetMethodCalls(
this ResolutionContext resolutionContext,
IConfigurationSection directive,
Expand Down Expand Up @@ -512,15 +531,33 @@ private static bool ParameterNameMatches(string actualParameterName, IEnumerable
return argValue.ConvertTo(method, collectionType, resolutionContext) as ICollection;
}

internal static string GetNameWithGenericArguments(this MethodInfo methodInfo)
internal static string GetNameWithGenericArguments(this MethodInfo methodInfo, string configKey)
{
if (methodInfo.IsGenericMethod)
{
return $"{methodInfo.Name}<{string.Join(", ", methodInfo.GetGenericArguments().Select(x => x.FullName))}>";
var typeArgs = methodInfo.GetGenericArguments().Select(x => x.FullName).ToArray();
#if Generator
for (var i = 0; i < typeArgs.Length; i++)
{
if (typeArgs[i] == "System.Object")
{
var idx = configKey.IndexOf("<") + 1;
if (configKey.Contains("@"))
{
idx = configKey.IndexOf("@") + 1;
}

var endIdx = configKey.IndexOf(">");
typeArgs[i] = configKey.Substring(idx, endIdx - idx);
}
}

#endif
return $"{methodInfo.Name}<{string.Join(", ", typeArgs)}>";
}
else
{
return methodInfo.Name;
return methodInfo.Name ?? configKey;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,20 @@ object CreateArray()
{
var elementType = toType.GetElementType();
var configurationElements = section.GetChildren().ToArray();
#if Generator
var result = new object();
#else
var result = Array.CreateInstance(elementType!, configurationElements.Length);
#endif
for (int i = 0; i < configurationElements.Length; ++i)
{
var argumentValue = configurationElements[i].GetArgumentValue(resolutionContext);
var value = argumentValue.ConvertTo(configurationMethod, elementType!, resolutionContext);
#if Generator
System.Diagnostics.Debug.WriteLine(value);
#else
result.SetValue(value, i);
#endif
}

return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,11 @@ public StringArgumentValue(IConfigurationSection section, string providedValue,

if (toTypeInfo.IsEnum)
{
return Enum.Parse(toType, argumentValue, true);
#if Generator
return true;
#else
return Enum.Parse(toType, argumentValue, true);
#endif
}

var convertor = ExtendedTypeConversions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" GeneratePathProperty="true" PrivateAssets="all" />
<PackageReference Include="System.Text.Json" Version="7.0.3" GeneratePathProperty="true" PrivateAssets="all" />
<PackageReference Include="System.Reflection.MetadataLoadContext" Version="7.0.0" GeneratePathProperty="true" PrivateAssets="all" />
<PackageReference Include="System.Reflection.Emit" Version="4.7.0" GeneratePathProperty="true" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
Expand All @@ -26,6 +27,7 @@
<None Include="$(PKGMicrosoft_Extensions_Configuration)\lib\netstandard2.0\Microsoft.Extensions.Configuration.dll" Pack="true" PackagePath="analyzers/dotnet/cs" />
<None Include="$(PKGMicrosoft_Extensions_Primitives)\lib\netstandard2.0\Microsoft.Extensions.Primitives.dll" Pack="true" PackagePath="analyzers/dotnet/cs" />
<None Include="$(PKGSystem_Reflection_MetadataLoadContext)\lib\netstandard2.0\System.Reflection.MetadataLoadContext.dll" Pack="true" PackagePath="analyzers/dotnet/cs" />
<None Include="$(PKGSystem_Reflection_Emit)\lib\netstandard2.0\System.Reflection.Emit.dll" Pack="true" PackagePath="analyzers/dotnet/cs" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" GeneratePathProperty="true" PrivateAssets="all" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" GeneratePathProperty="true" PrivateAssets="all" />
<PackageReference Include="System.Reflection.MetadataLoadContext" Version="7.0.0" GeneratePathProperty="true" PrivateAssets="all" />
<PackageReference Include="System.Reflection.Emit" Version="4.7.0" GeneratePathProperty="true" PrivateAssets="all" />
<PackageReference Include="System.Text.Json" Version="7.0.3" GeneratePathProperty="true" PrivateAssets="all" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="7.0.0" GeneratePathProperty="true" PrivateAssets="all" />
</ItemGroup>
Expand All @@ -46,6 +47,7 @@
<TargetPathWithTargetPlatformMoniker Include="$(PKGMicrosoft_Extensions_Configuration_Abstractions)\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll" IncludeRuntimeDependency="false" />
<TargetPathWithTargetPlatformMoniker Include="$(PKGMicrosoft_Extensions_Configuration)\lib\netstandard2.0\Microsoft.Extensions.Configuration.dll" IncludeRuntimeDependency="false" />
<TargetPathWithTargetPlatformMoniker Include="$(PKGMicrosoft_Extensions_Primitives)\lib\netstandard2.0\Microsoft.Extensions.Primitives.dll" IncludeRuntimeDependency="false" />
<TargetPathWithTargetPlatformMoniker Include="$(PKGSystem_Reflection_Emit)\lib\netstandard2.0\System.Reflection.Emit.dll" IncludeRuntimeDependency="false" />
<TargetPathWithTargetPlatformMoniker Include="$(PKGSystem_Reflection_MetadataLoadContext)\lib\netstandard2.0\System.Reflection.MetadataLoadContext.dll" IncludeRuntimeDependency="false" />
</ItemGroup>
</Target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,27 @@ public static IConfigurationArgumentValue GetArgumentValue(this IConfigurationSe
};

internal static object Get(this IConfiguration configuration, Type type)
=> throw new NotImplementedException();
{
if (configuration is IConfigurationSection sec)
{
if (type.FullName == typeof(string).FullName)
{
return sec.Value!;
}
else if (type.FullName == typeof(int).FullName)
{
return int.Parse(sec.Value);
}
else
{
return Convert.ChangeType(sec.Value, type);
}
}
else
{
throw new NotImplementedException();
}
}

internal static Delegate GenerateLambda(
this ResolutionContext resolutionContext,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.Reflection;
using System.Globalization;
using System.Reflection;
using ConfigurationProcessor.SourceGeneration.Utility;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Configuration;

namespace ConfigurationProcessor.Core.Implementation;
Expand All @@ -21,10 +23,11 @@ public TypeResolver CreateTypeResolver(string typeName, IConfiguration rootConfi
var newTypeName = typeName.Substring(1).ToString();
return (method, argIndex) =>
{
Type result;
if (newTypeName.IndexOf('@') >= 0)
{
var split = newTypeName.Split('@');
return EmitContext.CreateType(split[0], CreateTypeResolver(split[1], rootConfiguration, ambientConfiguration)(method, argIndex));
result = EmitContext.CreateType(split[0], CreateTypeResolver(split[1], rootConfiguration, ambientConfiguration)(method, argIndex));
}
else
{
Expand All @@ -33,8 +36,10 @@ public TypeResolver CreateTypeResolver(string typeName, IConfiguration rootConfi
throw new InvalidOperationException("Method cannot be null");
}

return EmitContext.CreateType(newTypeName);
result = EmitContext.CreateType(newTypeName);
}

return result;
};
}
else
Expand Down Expand Up @@ -63,6 +68,10 @@ private Type GetTypeInternal(string typeName)
{
return values.Single();
}
else if (EmitContext.CurrentAssembly.GetTypeByMetadataName(typeName) is INamedTypeSymbol typeSymbol)
{
return new FakeType(typeSymbol.Name, typeSymbol.ContainingNamespace.Name, null);
}
else
{
throw new InvalidOperationException($"Cannot find type {typeName}");
Expand Down
Loading
Loading