zelda/backend/pkg/utils/corev1.go

96 lines
2.2 KiB
Go
Raw Permalink Normal View History

2024-11-19 16:57:27 +08:00
package utils
import (
"fmt"
"strings"
v1 "k8s.io/api/core/v1"
apitypes "k8s.io/apimachinery/pkg/types"
)
func MergeEnv(mode MergeMode, envs ...[]v1.EnvVar) []v1.EnvVar {
envMap := make(map[string]v1.EnvVar)
for _, envvars := range envs {
for _, envvar := range envvars {
switch mode {
case MergeOverrideByFirst:
if _, ok := envMap[envvar.Name]; !ok {
envMap[envvar.Name] = envvar
}
case MergeOverrideByLatest:
envMap[envvar.Name] = envvar
case MergeValue:
if old, ok := envMap[envvar.Name]; !ok {
envMap[envvar.Name] = envvar
} else {
envMap[envvar.Name] = v1.EnvVar{
Name: envvar.Name,
Value: strings.Join([]string{old.Value, envvar.Value}, " "),
}
}
}
}
}
res := []v1.EnvVar{}
for _, v := range envMap {
res = append(res, v)
}
return res
}
func MergeObjectReferences(mergeMode MergeMode, orList ...[]v1.ObjectReference) ([]v1.ObjectReference, error) {
res := []v1.ObjectReference{}
if mergeMode == MergeValue {
return res, fmt.Errorf("cannot support merge value")
}
resMap := make(map[string]v1.ObjectReference)
for _, ors := range orList {
for _, or := range ors {
key := strings.Join([]string{or.Namespace, or.Name}, ".")
switch mergeMode {
case MergeOverrideByFirst:
if _, ok := resMap[key]; !ok {
resMap[key] = or
}
case MergeOverrideByLatest:
resMap[key] = or
}
}
}
for _, or := range resMap {
res = append(res, or)
}
return res, nil
}
func MergeLocalObjectReferences(mergeMode MergeMode, orList ...[]v1.LocalObjectReference) ([]v1.LocalObjectReference, error) {
res := []v1.LocalObjectReference{}
if mergeMode == MergeValue {
return res, fmt.Errorf("cannot support merge value")
}
resMap := make(map[string]v1.LocalObjectReference)
for _, ors := range orList {
for _, or := range ors {
switch mergeMode {
case MergeOverrideByFirst:
if _, ok := resMap[or.Name]; !ok {
resMap[or.Name] = or
}
case MergeOverrideByLatest:
resMap[or.Name] = or
}
}
}
for _, or := range resMap {
res = append(res, or)
}
return res, nil
}
func NamespacedNameFromObjectReference(ref v1.ObjectReference) apitypes.NamespacedName {
return apitypes.NamespacedName{
Namespace: ref.Namespace,
Name: ref.Name,
}
}