github.com/cloudfoundry-attic/ltc@v0.0.0-20151123212628-098adc7919fc/terminal/ui.go (about) 1 package terminal 2 3 import ( 4 "bufio" 5 "fmt" 6 "io" 7 "strings" 8 ) 9 10 //go:generate counterfeiter -o mocks/fake_password_reader.go . PasswordReader 11 type PasswordReader interface { 12 PromptForPassword(promptText string, args ...interface{}) string 13 } 14 15 type UI interface { 16 io.ReadWriter 17 PasswordReader 18 19 Prompt(promptText string, args ...interface{}) string 20 PromptWithDefault(promptText, defaultValue string, args ...interface{}) string 21 Say(format string, args ...interface{}) 22 SayIncorrectUsage(message string) 23 SayLine(format string, args ...interface{}) 24 SayNewLine() 25 } 26 27 type terminalUI struct { 28 io.Reader 29 io.Writer 30 PasswordReader 31 } 32 33 func NewUI(input io.Reader, output io.Writer, passwordReader PasswordReader) UI { 34 return &terminalUI{ 35 input, 36 output, 37 passwordReader, 38 } 39 } 40 41 func (t *terminalUI) Prompt(promptText string, args ...interface{}) string { 42 reader := bufio.NewReader(t) 43 fmt.Fprintf(t.Writer, promptText+": ", args...) 44 45 result, _ := reader.ReadString('\n') 46 return strings.TrimSpace(result) 47 } 48 49 func (t *terminalUI) PromptWithDefault(promptText, defaultValue string, args ...interface{}) string { 50 reader := bufio.NewReader(t) 51 fmt.Fprintf(t.Writer, promptText+fmt.Sprintf(" [%s]: ", defaultValue), args...) 52 53 result, _ := reader.ReadString('\n') 54 result = strings.TrimSpace(result) 55 56 if result == "" { 57 return defaultValue 58 } 59 60 return result 61 } 62 63 func (t *terminalUI) Say(format string, args ...interface{}) { 64 t.say(format, args...) 65 } 66 67 func (t *terminalUI) SayIncorrectUsage(message string) { 68 if len(message) > 0 { 69 t.say("Incorrect Usage: %s\n", message) 70 } else { 71 t.say("Incorrect Usage\n") 72 } 73 } 74 75 func (t *terminalUI) SayLine(format string, args ...interface{}) { 76 t.say(format+"\n", args...) 77 } 78 79 func (t *terminalUI) SayNewLine() { 80 t.say("\n") 81 } 82 83 func (t *terminalUI) say(format string, args ...interface{}) { 84 if len(args) > 0 { 85 t.Write([]byte(fmt.Sprintf(format, args...))) 86 return 87 } 88 t.Write([]byte(format)) 89 }