Skip to content

Commit 9babc75

Browse files
committed
Generic methods for working with K8S api
1 parent cfc4306 commit 9babc75

12 files changed

+1938
-8
lines changed

src/KubernetesClient/DryRun.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
using System.Runtime.Serialization;
2+
3+
namespace k8s
4+
{
5+
public enum DryRun
6+
{
7+
All
8+
}
9+
}

src/KubernetesClient/Extensions.cs

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
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+
}

src/KubernetesClient/IKubernetes.Generic.cs

Lines changed: 846 additions & 0 deletions
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)