diff --git a/backend/remote/backend.go b/backend/remote/backend.go index c5684ad9d9..d29ea06caf 100644 --- a/backend/remote/backend.go +++ b/backend/remote/backend.go @@ -496,16 +496,16 @@ func (b *Remote) cancel(cancelCtx context.Context, op *backend.Operation, runID // Colorize returns the Colorize structure that can be used for colorizing // output. This is guaranteed to always return a non-nil value and so useful // as a helper to wrap any potentially colored strings. -func (b *Remote) Colorize() *colorstring.Colorize { - if b.CLIColor != nil { - return b.CLIColor - } - - return &colorstring.Colorize{ - Colors: colorstring.DefaultColors, - Disable: true, - } -} +// func (b *Remote) Colorize() *colorstring.Colorize { +// if b.CLIColor != nil { +// return b.CLIColor +// } + +// return &colorstring.Colorize{ +// Colors: colorstring.DefaultColors, +// Disable: true, +// } +// } func generalError(msg string, err error) error { if urlErr, ok := err.(*url.Error); ok { diff --git a/backend/remote/colorize.go b/backend/remote/colorize.go new file mode 100644 index 0000000000..0f877c0077 --- /dev/null +++ b/backend/remote/colorize.go @@ -0,0 +1,47 @@ +package remote + +import ( + "regexp" + + "github.com/mitchellh/colorstring" +) + +// colorsRe is used to find ANSI escaped color codes. +var colorsRe = regexp.MustCompile("\033\\[\\d{1,3}m") + +// Colorer is the interface that must be implemented to colorize strings. +type Colorer interface { + Color(v string) string +} + +// Colorize is used to print output when the -no-color flag is used. It will +// strip all ANSI escaped color codes which are set while the operation was +// executed in Terraform Enterprise. +// +// When Terraform Enterprise supports run specific variables, this code can be +// removed as we can then pass the CLI flag to the backend and prevent the color +// codes from being written to the output. +type Colorize struct { + cliColor *colorstring.Colorize +} + +// Color will strip all ANSI escaped color codes and return a uncolored string. +func (c *Colorize) Color(v string) string { + return colorsRe.ReplaceAllString(c.cliColor.Color(v), "") +} + +// Colorize returns the Colorize structure that can be used for colorizing +// output. This is guaranteed to always return a non-nil value and so is useful +// as a helper to wrap any potentially colored strings. +func (b *Remote) Colorize() Colorer { + if b.CLIColor != nil && !b.CLIColor.Disable { + return b.CLIColor + } + if b.CLIColor != nil { + return &Colorize{cliColor: b.CLIColor} + } + return &Colorize{cliColor: &colorstring.Colorize{ + Colors: colorstring.DefaultColors, + Disable: true, + }} +}