github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/output/colorpicker.go (about)

     1  /*
     2  Copyright 2021 The Skaffold Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package output
    18  
    19  import (
    20  	tag "github.com/GoogleContainerTools/skaffold/pkg/skaffold/tag/util"
    21  )
    22  
    23  type ColorPicker interface {
    24  	AddImage(string)
    25  	Pick(string) Color
    26  }
    27  
    28  // ColorPicker associates colors with images such that container logs can be output to
    29  // the terminal with a consistent color being used to identify individual log streams.
    30  type colorPicker struct {
    31  	imageColors map[string]Color
    32  }
    33  
    34  // NewColorPicker creates a new ColorPicker.
    35  func NewColorPicker() ColorPicker {
    36  	imageColors := make(map[string]Color)
    37  
    38  	return &colorPicker{
    39  		imageColors: imageColors,
    40  	}
    41  }
    42  
    43  // AddImage adds an image to the ColorPicker. Each image added will be paired with a color
    44  // selected sequentially from `DefaultColorCodes`. If all colors are used, the first color
    45  // will be used again. The formatter for the associated color will then be returned by `Pick`
    46  // each time it is called for the artifact and can be used to write to out in that color.
    47  func (p *colorPicker) AddImage(image string) {
    48  	imageName := tag.StripTag(image, false)
    49  	if _, ok := p.imageColors[imageName]; ok {
    50  		return
    51  	}
    52  	p.imageColors[imageName] = DefaultColorCodes[len(p.imageColors)%len(DefaultColorCodes)]
    53  }
    54  
    55  // Pick will return the color that was associated with the image when it was added to the
    56  // ColorPicker. If no color was associated with the image, the none color will be returned,
    57  // which will write with no formatting.
    58  func (p *colorPicker) Pick(image string) Color {
    59  	if c, present := p.imageColors[tag.StripTag(image, false)]; present {
    60  		return c
    61  	}
    62  
    63  	// If no mapping is found, don't add any color formatting
    64  	return None
    65  }