Skip to content

Commit

Permalink
Add EnumMemberAttribute and .NET 9's JsonStringEnumMemberNameAttribut…
Browse files Browse the repository at this point in the history
…e handling for CRD generation.
  • Loading branch information
wasabii committed Jan 4, 2025
1 parent f0eb626 commit d791407
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
37 changes: 36 additions & 1 deletion src/KubeOps.Transpiler/Crds.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Collections;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;

using k8s;
Expand Down Expand Up @@ -336,12 +337,46 @@ private static V1JSONSchemaProps Map(this MetadataLoadContext context, Type type
"System.Enum" => new V1JSONSchemaProps
{
Type = String,
EnumProperty = Enum.GetNames(type).Cast<object>().ToList(),
EnumProperty = GetEnumNames(context, type),
},
_ => throw InvalidType(type),
};
}

private static IList<object> GetEnumNames(this MetadataLoadContext context, Type type)
{
var attributeNameByFieldName = new Dictionary<string, string>();
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (field.GetCustomAttribute<EnumMemberAttribute>() is { Value: not null } enumMemberAtribute)
{
attributeNameByFieldName.Add(field.Name, enumMemberAtribute.Value);
}

#if NET9_0_OR_GREATER
if (field.GetCustomAttribute<JsonStringEnumMemberNameAttribute>() is { Name: not null } stringEnumMemberAttribute)
{
attributeNameByFieldName.Add(field.Name, stringEnumMemberAttribute.Name);
}
#endif
}

var enumName = new List<object>();
foreach (var value in Enum.GetNames(type))
{
if (attributeNameByFieldName.TryGetValue(value, out var name))
{
enumName.Add(name);
}
else
{
enumName.Add(value);
}
}

return enumName;
}

private static V1JSONSchemaProps MapObjectType(this MetadataLoadContext context, Type type)
{
switch (type.FullName)
Expand Down
2 changes: 1 addition & 1 deletion src/KubeOps.Transpiler/KubeOps.Transpiler.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<TargetFrameworks>net6.0;net7.0;net8.0;net9.0</TargetFrameworks>
</PropertyGroup>

<PropertyGroup>
Expand Down

0 comments on commit d791407

Please sign in to comment.