forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathversion.go
118 lines (109 loc) · 2.39 KB
/
version.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package kube
import (
"strings"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// GetVersion returns the version from the labels on the deployment if it can be deduced
func GetVersion(r *metav1.ObjectMeta) string {
if r != nil {
labels := r.Labels
if labels != nil {
v := labels["version"]
if v != "" {
return v
}
v = labels["chart"]
if v != "" {
arr := strings.Split(v, "-")
last := arr[len(arr)-1]
if last != "" {
return last
}
return v
}
}
}
return ""
}
// GetPodVersion returns the version for the given app name
func GetPodVersion(pod *corev1.Pod, appName string) string {
v := GetVersion(&pod.ObjectMeta)
if v != "" {
return v
}
if appName == "" {
appName = GetName(&pod.ObjectMeta)
}
if appName != "" {
for _, c := range pod.Spec.Containers {
image := c.Image
idx := strings.LastIndex(image, ":")
if idx > 0 {
version := image[idx+1:]
prefix := image[0:idx]
if prefix == appName || strings.HasSuffix(prefix, "/"+appName) {
return version
}
}
}
}
return ""
}
// GetName returns the app name
func GetName(r *metav1.ObjectMeta) string {
if r != nil {
ns := r.Namespace
labels := r.Labels
if labels != nil {
name := labels["app"]
if name != "" {
// for helm deployments which prefix the namespace in the name lets strip it
prefix := ns + "-"
if strings.HasPrefix(name, prefix) {
name = strings.TrimPrefix(name, prefix)
// we often have the app name repeated twice!
l := len(name) / 2
if name[l] == '-' {
first := name[0:l]
if name[l+1:] == first {
return first
}
}
}
return name
}
}
name := r.Name
if ns != "" {
// for helm deployments which prefix the namespace in the name lets strip it
prefix := ns + "-"
if strings.HasPrefix(name, prefix) {
name = strings.TrimPrefix(name, prefix)
return name
}
}
return name
}
return ""
}
// GetCommitSha returns the git commit sha
func GetCommitSha(r *metav1.ObjectMeta) string {
if r != nil {
annotations := r.Annotations
if annotations != nil {
return annotations["jenkins.io/git-sha"]
}
}
return ""
}
// GetCommitURL returns the git commit URL
func GetCommitURL(r *metav1.ObjectMeta) string {
if r != nil {
annotations := r.Annotations
if annotations != nil {
return annotations["jenkins.io/git-url"]
}
}
return ""
}