Skip to content

Commit 13c3342

Browse files
committed
copy k8snamehash function to library
1 parent ab63d98 commit 13c3342

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ The `pkg/controller` package contains useful functions for setting up and runnin
103103
#### Noteworthy Functions
104104

105105
- `LoadKubeconfig` creates a REST config for accessing a k8s cluster. It can be used with a path to a kubeconfig file, or a directory containing files for a trust relationship. When called with an empty path, it returns the in-cluster configuration.
106+
- There are some functions useful for working with annotations and labels, e.g. `HasAnnotationWithValue` or `EnsureLabel`.
107+
- There are multiple predefined predicates to help with filtering reconciliation triggers in controllers, e.g. `HasAnnotationPredicate` or `DeletionTimestampChangedPredicate`.
108+
- The `K8sNameHash` function can be used to create a hash that can be used as a name for k8s resources.
106109

107110
### logging
108111

pkg/controller/utils.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package controller
2+
3+
import (
4+
"crypto/sha1"
5+
"encoding/base32"
6+
"reflect"
7+
"strings"
8+
)
9+
10+
const (
11+
maxLength int = 63
12+
Base32EncodeStdLowerCase = "abcdefghijklmnopqrstuvwxyz234567"
13+
)
14+
15+
// K8sNameHash takes any number of string arguments and computes a hash out of it, which is then base32-encoded to be a valid k8s resource name.
16+
// The arguments are joined with '/' before being hashed.
17+
func K8sNameHash(ids ...string) string {
18+
name := strings.Join(ids, "/")
19+
h := sha1.New()
20+
_, _ = h.Write([]byte(name))
21+
// we need base32 encoding as some base64 (even url safe base64) characters are not supported by k8s
22+
// see https://kubernetes.io/docs/concepts/overview/working-with-objects/names/
23+
return base32.NewEncoding(Base32EncodeStdLowerCase).WithPadding(base32.NoPadding).EncodeToString(h.Sum(nil))
24+
}
25+
26+
// IsNil checks if a given pointer is nil.
27+
// Opposed to 'i == nil', this works for typed and untyped nil values.
28+
func IsNil(i any) bool {
29+
if i == nil {
30+
return true
31+
}
32+
switch reflect.TypeOf(i).Kind() {
33+
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice:
34+
return reflect.ValueOf(i).IsNil()
35+
}
36+
return false
37+
}

0 commit comments

Comments
 (0)