generated from cloudoperators/repository-template
/
util.go
80 lines (71 loc) · 2.56 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Greenhouse contributors
// SPDX-License-Identifier: Apache-2.0
package clientutil
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/version"
"k8s.io/cli-runtime/pkg/genericclioptions"
"sigs.k8s.io/controller-runtime/pkg/client"
greenhousev1alpha1 "github.com/cloudoperators/greenhouse/pkg/apis/greenhouse/v1alpha1"
)
// IsSecretContainsKey checks whether the given secret contains a key.
func IsSecretContainsKey(s *corev1.Secret, key string) bool {
if s.Data == nil {
return false
}
v, ok := s.Data[key]
return ok && v != nil
}
// GetSecretKeyFromSecretKeyReference returns the value of the secret identified by SecretKeyReference or an error.
func GetSecretKeyFromSecretKeyReference(ctx context.Context, c client.Client, namespace string, secretReference greenhousev1alpha1.SecretKeyReference) (string, error) {
var secret = new(corev1.Secret)
if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: secretReference.Name}, secret); err != nil {
return "", err
}
if v, ok := secret.Data[secretReference.Key]; ok {
// Trim newline characters from the end of the string.
stringValue := string(v)
stringValue = strings.TrimRight(stringValue, "\n")
return stringValue, nil
}
return "", fmt.Errorf("secret %s/%s does not contain key %s", namespace, secretReference.Name, secretReference.Key)
}
// GetKubernetesVersion returns the kubernetes git version using the discovery client.
func GetKubernetesVersion(restClientGetter genericclioptions.RESTClientGetter) (*version.Info, error) {
dc, err := restClientGetter.ToDiscoveryClient()
if err != nil {
return nil, err
}
return dc.ServerVersion()
}
// Searches for a directory upwards starting from the given path.
func FindDirUpwards(path, dirName string, maxSteps int) (string, error) {
return findRecursively(path, dirName, maxSteps, 0)
}
func findRecursively(path, dirName string, maxSteps, steps int) (string, error) {
if path == "/" {
return "", fmt.Errorf("root reached. directory not found: %s", dirName)
}
if maxSteps == steps {
return "", fmt.Errorf("max steps reached. directory not found: %s", dirName)
}
absPath, err := filepath.Abs(path)
if err != nil {
return "", err
}
dirPath := filepath.Join(absPath, dirName)
if _, err = os.Stat(dirPath); err != nil {
if os.IsNotExist(err) {
steps++
return findRecursively(filepath.Join(absPath, ".."), dirName, maxSteps, steps)
}
return "", err
}
return dirPath, nil
}