command/*: colors on error messages (red)

This commit is contained in:
Mitchell Hashimoto 2014-07-12 20:59:16 -07:00
parent 77bfa5657e
commit 79c60e0331
3 changed files with 72 additions and 2 deletions

42
command/cli_ui.go Normal file
View File

@ -0,0 +1,42 @@
package command
import (
"fmt"
"github.com/mitchellh/cli"
"github.com/mitchellh/colorstring"
)
// ColoredUi is a Ui implementation that colors its output according
// to the given color schemes for the given type of output.
type ColorizeUi struct {
Colorize *colorstring.Colorize
OutputColor string
InfoColor string
ErrorColor string
Ui cli.Ui
}
func (u *ColorizeUi) Ask(query string) (string, error) {
return u.Ui.Ask(u.colorize(query, u.OutputColor))
}
func (u *ColorizeUi) Output(message string) {
u.Ui.Output(u.colorize(message, u.OutputColor))
}
func (u *ColorizeUi) Info(message string) {
u.Ui.Info(u.colorize(message, u.InfoColor))
}
func (u *ColorizeUi) Error(message string) {
u.Ui.Error(u.colorize(message, u.ErrorColor))
}
func (u *ColorizeUi) colorize(message string, color string) string {
if color == "" {
return message
}
return u.Colorize.Color(fmt.Sprintf("%s%s[reset]", color, message))
}

11
command/cli_ui_test.go Normal file
View File

@ -0,0 +1,11 @@
package command
import (
"testing"
"github.com/mitchellh/cli"
)
func TestColorizeUi_impl(t *testing.T) {
var _ cli.Ui = new(ColorizeUi)
}

View File

@ -15,6 +15,8 @@ type Meta struct {
Color bool Color bool
ContextOpts *terraform.ContextOpts ContextOpts *terraform.ContextOpts
Ui cli.Ui Ui cli.Ui
oldUi cli.Ui
} }
// Colorize returns the colorization structure for a command. // Colorize returns the colorization structure for a command.
@ -104,15 +106,30 @@ func (m *Meta) contextOpts() *terraform.ContextOpts {
// will potentially modify the args in-place. It will return the resulting // will potentially modify the args in-place. It will return the resulting
// slice. // slice.
func (m *Meta) process(args []string) []string { func (m *Meta) process(args []string) []string {
m.Color = true // We do this so that we retain the ability to technically call
// process multiple times, even if we have no plans to do so
if m.oldUi != nil {
m.Ui = m.oldUi
}
// Set colorization
m.Color = true
for i, v := range args { for i, v := range args {
if v == "-no-color" { if v == "-no-color" {
m.Color = false m.Color = false
return append(args[:i], args[i+1:]...) args = append(args[:i], args[i+1:]...)
break
} }
} }
// Set the UI
m.oldUi = m.Ui
m.Ui = &ColorizeUi{
Colorize: m.Colorize(),
ErrorColor: "[red]",
Ui: m.oldUi,
}
return args return args
} }