github.com/hernad/nomad@v1.6.112/command/ui/writer_ui.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package ui 5 6 import ( 7 "errors" 8 "fmt" 9 "io" 10 11 "github.com/mitchellh/cli" 12 ) 13 14 // WriterUI is an implementation of the cli.Ui interface which can be used for 15 // commands that need to have direct access to the underlying UI readers and 16 // writers. 17 type WriterUI struct { 18 // Ui is the wrapped cli.Ui that supplies the functions for the thin shims 19 Ui cli.Ui 20 21 reader io.Reader 22 writer io.Writer 23 errorWriter io.Writer 24 25 // baseUi stores the basic UI that was used to create this WriterUI. It 26 // allows us to call its functions and not implement them again. 27 baseUi cli.Ui 28 } 29 30 // NewWriterUI generates a new cli.Ui that can be used for commands that 31 // need access to the underlying UI's writers for copying large amounts of 32 // data without local buffering. The caller is required to pass a UI 33 // chain ending in a cli.BasicUi (or a cli.MockUi for testing). 34 // 35 // Currently, the UIs in the chain need to be pointers to a cli.ColoredUi, 36 // cli.BasicUi, or cli.MockUi to work correctly. 37 func NewWriterUI(ui cli.Ui) (*WriterUI, error) { 38 var done bool 39 wUI := WriterUI{Ui: ui} 40 41 for !done { 42 if ui == nil { 43 break 44 } 45 46 switch u := ui.(type) { 47 case *cli.MockUi: 48 wUI.reader = u.InputReader 49 wUI.writer = u.OutputWriter 50 wUI.errorWriter = u.ErrorWriter 51 wUI.baseUi = u 52 done = true 53 case *cli.BasicUi: 54 wUI.reader = u.Reader 55 wUI.writer = u.Writer 56 wUI.errorWriter = u.ErrorWriter 57 wUI.baseUi = u 58 done = true 59 case *cli.ColoredUi: 60 ui = u.Ui 61 default: 62 return nil, fmt.Errorf("writer ui: unsupported Ui type: %T", ui) 63 } 64 } 65 66 if !done { 67 return nil, errors.New("failed to generate command UI") 68 } 69 70 return &wUI, nil 71 } 72 73 func (w *WriterUI) InputReader() io.Reader { return w.reader } 74 func (w *WriterUI) OutputWriter() io.Writer { return w.writer } 75 func (w *WriterUI) ErrorWriter() io.Writer { return w.errorWriter } 76 77 func (w *WriterUI) Output(message string) { w.Ui.Output(message) } 78 func (w *WriterUI) Info(message string) { w.Ui.Info(message) } 79 func (w *WriterUI) Warn(message string) { w.Ui.Warn(message) } 80 func (w *WriterUI) Error(message string) { w.Ui.Error(message) } 81 82 func (w *WriterUI) Ask(query string) (string, error) { return w.Ui.Ask(query) } 83 func (w *WriterUI) AskSecret(query string) (string, error) { return w.Ui.AskSecret(query) }