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