github.com/hugorut/terraform@v1.1.3/src/backend/remote/colorize.go (about)

     1  package remote
     2  
     3  import (
     4  	"regexp"
     5  
     6  	"github.com/mitchellh/colorstring"
     7  )
     8  
     9  // TODO SvH: This file should be deleted and the type cliColorize should be
    10  // renamed back to Colorize as soon as we can pass -no-color to the backend.
    11  
    12  // colorsRe is used to find ANSI escaped color codes.
    13  var colorsRe = regexp.MustCompile("\033\\[\\d{1,3}m")
    14  
    15  // Colorer is the interface that must be implemented to colorize strings.
    16  type Colorer interface {
    17  	Color(v string) string
    18  }
    19  
    20  // Colorize is used to print output when the -no-color flag is used. It will
    21  // strip all ANSI escaped color codes which are set while the operation was
    22  // executed in Terraform Enterprise.
    23  //
    24  // When Terraform Enterprise supports run specific variables, this code can be
    25  // removed as we can then pass the CLI flag to the backend and prevent the color
    26  // codes from being written to the output.
    27  type Colorize struct {
    28  	cliColor *colorstring.Colorize
    29  }
    30  
    31  // Color will strip all ANSI escaped color codes and return a uncolored string.
    32  func (c *Colorize) Color(v string) string {
    33  	return colorsRe.ReplaceAllString(c.cliColor.Color(v), "")
    34  }
    35  
    36  // Colorize returns the Colorize structure that can be used for colorizing
    37  // output. This is guaranteed to always return a non-nil value and so is useful
    38  // as a helper to wrap any potentially colored strings.
    39  func (b *Remote) Colorize() Colorer {
    40  	if b.CLIColor != nil && !b.CLIColor.Disable {
    41  		return b.CLIColor
    42  	}
    43  	if b.CLIColor != nil {
    44  		return &Colorize{cliColor: b.CLIColor}
    45  	}
    46  	return &Colorize{cliColor: &colorstring.Colorize{
    47  		Colors:  colorstring.DefaultColors,
    48  		Disable: true,
    49  	}}
    50  }