Files
csharp/src/KubernetesClient/Extensions.cs
Boshi Lian 16845bae1d Style fix1 (#512)
* fix SA1505 and SA1508

* fix SA1116

* fix SA1009

* fix SA1019

* fix SA1127

* fix SA1128

* fix SA1134

* fix indent

* allow CA2227

* fix CA1810

* using clean up

* fix naming

* fix CA1806

* fix await

* Revert "fix CA1806"

This reverts commit a3b465087fdaf26ec461272373ee9810a90de2cc.

* fix dotnet format

* allow SA1009
2020-11-01 12:24:51 -08:00

42 lines
1.4 KiB
C#

using System;
using System.Reflection;
using System.Text.RegularExpressions;
using k8s.Models;
namespace k8s
{
public static class Extensions
{
public static KubernetesEntityAttribute GetKubernetesTypeMetadata<T>(this T obj)
where T : IKubernetesObject
=>
obj.GetType().GetKubernetesTypeMetadata();
public static KubernetesEntityAttribute GetKubernetesTypeMetadata(this Type currentType)
{
var attr = currentType.GetCustomAttribute<KubernetesEntityAttribute>();
if (attr == null)
{
throw new InvalidOperationException($"Custom resource must have {nameof(KubernetesEntityAttribute)} applied to it");
}
return attr;
}
public static T Initialize<T>(this T obj)
where T : IKubernetesObject
{
var metadata = obj.GetKubernetesTypeMetadata();
obj.ApiVersion = !string.IsNullOrEmpty(metadata.Group) ? $"{metadata.Group}/{metadata.ApiVersion}" : metadata.ApiVersion;
obj.Kind = metadata.Kind ?? obj.GetType().Name;
if (obj is IMetadata<V1ObjectMeta> withMetadata && withMetadata.Metadata == null)
{
withMetadata.Metadata = new V1ObjectMeta();
}
return obj;
}
internal static bool IsValidKubernetesName(this string value) => !Regex.IsMatch(value, "^[a-z0-9-]+$");
}
}