-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
merge.go
101 lines (89 loc) · 2.61 KB
/
merge.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package util
import (
"encoding/json"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/strategicpatch"
wfv1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
)
// MergeTo will merge one workflow (the "patch" workflow) into another (the "target" workflow.
// If the target workflow defines a field, this take precedence over the patch.
func MergeTo(patch, target *wfv1.Workflow) error {
if target == nil || patch == nil {
return nil
}
patchWfBytes, err := json.Marshal(patch)
if err != nil {
return err
}
targetWfByte, err := json.Marshal(target)
if err != nil {
return err
}
var mergedWfByte []byte
mergedWfByte, err = strategicpatch.StrategicMergePatch(patchWfBytes, targetWfByte, wfv1.Workflow{})
if err != nil {
return err
}
err = json.Unmarshal(mergedWfByte, target)
if err != nil {
return err
}
return nil
}
// mergeMap will merge all element from right map to left map if it is not present in left.
func mergeMap(from, to map[string]string) {
for key, val := range from {
if _, ok := to[key]; !ok {
to[key] = val
}
}
}
// JoinWorkflowMetaData will join the workflow metadata with the following order of preference
// 1. Workflow, 2 WorkflowTemplate (WorkflowTemplateRef), 3. WorkflowDefault.
func JoinWorkflowMetaData(wfMetaData, wftMetaData, wfDefaultMetaData *metav1.ObjectMeta) {
if wftMetaData != nil {
mergeMetaDataTo(wftMetaData, wfMetaData)
}
if wfDefaultMetaData != nil {
mergeMetaDataTo(wfDefaultMetaData, wfMetaData)
}
}
// JoinWorkflowSpec will join the workflow specs with the following order of preference
// 1. Workflow Spec, 2 WorkflowTemplate Spec (WorkflowTemplateRef), 3. WorkflowDefault Spec.
func JoinWorkflowSpec(wfSpec, wftSpec, wfDefaultSpec *wfv1.WorkflowSpec) (*wfv1.Workflow, error) {
if wfSpec == nil {
return nil, nil
}
targetWf := wfv1.Workflow{Spec: *wfSpec.DeepCopy()}
if wftSpec != nil {
err := MergeTo(&wfv1.Workflow{Spec: *wftSpec.DeepCopy()}, &targetWf)
if err != nil {
return nil, err
}
}
if wfDefaultSpec != nil {
err := MergeTo(&wfv1.Workflow{Spec: *wfDefaultSpec.DeepCopy()}, &targetWf)
if err != nil {
return nil, err
}
}
return &targetWf, nil
}
// mergeMetadata will merge the labels and annotations into the target metadata.
func mergeMetaDataTo(from, to *metav1.ObjectMeta) {
if from == nil {
return
}
if from.Labels != nil {
if to.Labels == nil {
to.Labels = make(map[string]string)
}
mergeMap(from.Labels, to.Labels)
}
if from.Annotations != nil {
if to.Annotations == nil {
to.Annotations = make(map[string]string)
}
mergeMap(from.Annotations, to.Annotations)
}
}