|
| 1 | +using System; |
| 2 | +using System.Collections; |
| 3 | +using System.Reflection; |
| 4 | +using System.Text.RegularExpressions; |
| 5 | +using k8s.Models; |
| 6 | + |
| 7 | +namespace k8s |
| 8 | +{ |
| 9 | + public static class Extensions |
| 10 | + { |
| 11 | + public static KubernetesEntityAttribute GetKubernetesTypeMetadata<T>(this T obj) where T : IKubernetesObject |
| 12 | + { |
| 13 | + return obj.GetType().GetKubernetesTypeMetadata(); |
| 14 | + } |
| 15 | + |
| 16 | + public static KubernetesEntityAttribute GetKubernetesTypeMetadata(this Type currentType) |
| 17 | + { |
| 18 | + var attr = currentType.GetCustomAttribute<KubernetesEntityAttribute>(); |
| 19 | + if (attr == null) |
| 20 | + { |
| 21 | + throw new InvalidOperationException($"Custom resource must have {nameof(KubernetesEntityAttribute)} applied to it"); |
| 22 | + } |
| 23 | + |
| 24 | + return attr; |
| 25 | + } |
| 26 | + |
| 27 | + public static T Initialize<T>(this T obj) where T : IKubernetesObject |
| 28 | + { |
| 29 | + var metadata = obj.GetKubernetesTypeMetadata(); |
| 30 | + |
| 31 | + obj.ApiVersion = !string.IsNullOrEmpty(metadata.Group) ? $"{metadata.Group}/{metadata.ApiVersion}" : metadata.ApiVersion; |
| 32 | + obj.Kind = metadata.Kind ?? obj.GetType().Name; |
| 33 | + if (obj is IMetadata<V1ObjectMeta> withMetadata && withMetadata.Metadata == null) |
| 34 | + { |
| 35 | + withMetadata.Metadata = new V1ObjectMeta(); |
| 36 | + } |
| 37 | + |
| 38 | + return obj; |
| 39 | + } |
| 40 | + |
| 41 | + internal static bool IsValidKubernetesName(this string value) |
| 42 | + { |
| 43 | + return !Regex.IsMatch(value, "^[a-z0-9-]+$"); |
| 44 | + } |
| 45 | + |
| 46 | + // Convert the string to camel case. |
| 47 | + public static string ToCamelCase(this string value) |
| 48 | + { |
| 49 | + // If there are 0 or 1 characters, just return the string. |
| 50 | + if (value == null || value.Length < 2) |
| 51 | + { |
| 52 | + return value; |
| 53 | + } |
| 54 | + |
| 55 | + // Split the string into words. |
| 56 | + var words = value.Split( |
| 57 | + new char[0], |
| 58 | + StringSplitOptions.RemoveEmptyEntries); |
| 59 | + |
| 60 | + // Combine the words. |
| 61 | + var result = words[0].ToLower(); |
| 62 | + for (var i = 1; i < words.Length; i++) |
| 63 | + { |
| 64 | + result += |
| 65 | + words[i].Substring(0, 1).ToUpper() + |
| 66 | + words[i].Substring(1); |
| 67 | + } |
| 68 | + |
| 69 | + return result; |
| 70 | + } |
| 71 | + |
| 72 | + public static bool In<T>(this T obj, params T[] values) => ((IList)values).Contains(obj); |
| 73 | + |
| 74 | + } |
| 75 | +} |
0 commit comments