github.com/spinnaker/spin@v1.30.0/cmd/output/cli_ui.go (about) 1 // Copyright (c) 2018, Google, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package output 16 17 import ( 18 "fmt" 19 "io" 20 21 "github.com/mitchellh/cli" 22 "github.com/mitchellh/colorstring" 23 ) 24 25 type Ui interface { 26 Success(message string) 27 JsonOutput(data interface{}) 28 cli.Ui 29 } 30 31 type ColorizeUi struct { 32 Colorize *colorstring.Colorize 33 OutputColor string 34 InfoColor string 35 ErrorColor string 36 WarnColor string 37 SuccessColor string 38 Ui cli.Ui 39 Quiet bool 40 OutputFormater OutputFormater 41 } 42 43 func NewUI( 44 quiet, color bool, 45 outputFormater OutputFormater, 46 outWriter, errWriter io.Writer, 47 ) *ColorizeUi { 48 return &ColorizeUi{ 49 Colorize: &colorstring.Colorize{ 50 Colors: colorstring.DefaultColors, 51 Disable: !color, 52 Reset: true, 53 }, 54 ErrorColor: "[red]", 55 WarnColor: "[yellow]", 56 InfoColor: "[blue]", 57 SuccessColor: "[bold][green]", 58 Ui: &cli.BasicUi{ 59 Writer: outWriter, 60 ErrorWriter: errWriter, 61 }, 62 Quiet: quiet, 63 OutputFormater: outputFormater, 64 } 65 } 66 67 func (u *ColorizeUi) Ask(query string) (string, error) { 68 return u.Ui.Ask(u.colorize(query, u.OutputColor)) 69 } 70 71 func (u *ColorizeUi) AskSecret(query string) (string, error) { 72 return u.Ui.AskSecret(u.colorize(query, u.OutputColor)) 73 } 74 75 func (u *ColorizeUi) Output(message string) { 76 u.Ui.Output(u.colorize(message, u.OutputColor)) 77 } 78 79 // JsonOutput prints the data specified using the configured OutputFormater. 80 func (u *ColorizeUi) JsonOutput(data interface{}) { 81 output, err := u.OutputFormater(data) 82 if err != nil { 83 u.Error(fmt.Sprintf("%v", err)) 84 } 85 u.Output(string(output)) 86 } 87 88 func (u *ColorizeUi) Success(message string) { 89 if !u.Quiet { 90 u.Ui.Info(u.colorize(message, u.SuccessColor)) 91 } 92 } 93 94 func (u *ColorizeUi) Info(message string) { 95 if !u.Quiet { 96 u.Ui.Info(u.colorize(message, u.InfoColor)) 97 } 98 } 99 100 func (u *ColorizeUi) Error(message string) { 101 u.Ui.Error(u.colorize(message, u.ErrorColor)) 102 } 103 104 func (u *ColorizeUi) Warn(message string) { 105 if !u.Quiet { 106 u.Ui.Warn(u.colorize(message, u.WarnColor)) 107 } 108 } 109 110 func (u *ColorizeUi) colorize(message string, color string) string { 111 if color == "" { 112 return message 113 } 114 115 return u.Colorize.Color(fmt.Sprintf("%s%s", color, message)) 116 }