/
colorpicker.go
84 lines (70 loc) · 2.45 KB
/
colorpicker.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
/*
Copyright 2018 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"strings"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/color"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/v1alpha2"
v1 "k8s.io/api/core/v1"
)
var colorCodes = []color.Color{
color.LightRed,
color.LightGreen,
color.LightYellow,
color.LightBlue,
color.LightPurple,
color.Red,
color.Green,
color.Yellow,
color.Blue,
color.Purple,
color.Cyan,
}
// ColorPicker is used to associate colors for with pods so that the container logs
// can be output to the terminal with a consistent color being used to identify logs
// from each pod.
type ColorPicker interface {
Pick(pod *v1.Pod) color.Color
}
type colorPicker struct {
imageColors map[string]color.Color
}
// NewColorPicker creates a new ColorPicker. For each artfact, a color will be selected
// sequentially from `colorCodes`. If all colors are used, the first color will be used
// again. The formatter for the associated color will then be returned by `Pick` each
// time it is called for the artifact and can be used to write to out in that color.
func NewColorPicker(artifacts []*v1alpha2.Artifact) ColorPicker {
c := colorPicker{imageColors: map[string]color.Color{}}
for i, artifact := range artifacts {
c.imageColors[artifact.ImageName] = colorCodes[i%len(colorCodes)]
}
return &c
}
// Pick will return the color that was associated with pod when `NewColorPicker` was called.
// If no color was associated with the pod, the none color will be returned, which will
// write with no formatting.
func (p *colorPicker) Pick(pod *v1.Pod) color.Color {
for _, container := range pod.Spec.Containers {
if c, present := p.imageColors[stripTag(container.Image)]; present {
return c
}
}
// If no mapping is found, don't add any color formatting
return color.None
}
func stripTag(image string) string {
if !strings.Contains(image, ":") {
return image
}
return strings.SplitN(image, ":", 2)[0]
}