2020-05-20 19:28:19 -04:00
|
|
|
using System;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
using System.Text.RegularExpressions;
|
|
|
|
|
using k8s.Models;
|
|
|
|
|
|
|
|
|
|
namespace k8s
|
|
|
|
|
{
|
|
|
|
|
public static class Extensions
|
|
|
|
|
{
|
2020-11-01 12:24:51 -08:00
|
|
|
public static KubernetesEntityAttribute GetKubernetesTypeMetadata<T>(this T obj)
|
|
|
|
|
where T : IKubernetesObject
|
|
|
|
|
=>
|
2020-05-20 19:28:19 -04:00
|
|
|
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");
|
|
|
|
|
}
|
2020-10-23 08:31:57 -07:00
|
|
|
|
2020-05-20 19:28:19 -04:00
|
|
|
return attr;
|
|
|
|
|
}
|
|
|
|
|
|
2020-11-01 12:24:51 -08:00
|
|
|
public static T Initialize<T>(this T obj)
|
|
|
|
|
where T : IKubernetesObject
|
2020-05-20 19:28:19 -04:00
|
|
|
{
|
|
|
|
|
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-]+$");
|
|
|
|
|
}
|
|
|
|
|
}
|