check IsTerminal once
Vladimir Bauer
7 years ago
| 24 | 24 | // Writer is a buffered the writer that updates the terminal. |
| 25 | 25 | // The contents of writer will be flushed when Flush is called. |
| 26 | 26 | type Writer struct { |
| 27 | out io.Writer | |
| 28 | buf bytes.Buffer | |
| 29 | lineCount int | |
| 27 | out io.Writer | |
| 28 | buf bytes.Buffer | |
| 29 | isTerminal bool | |
| 30 | fd int | |
| 31 | lineCount int | |
| 30 | 32 | } |
| 31 | 33 | |
| 32 | 34 | // New returns a new Writer with defaults |
| 33 | func New(w io.Writer) *Writer { | |
| 34 | return &Writer{out: w} | |
| 35 | func New(out io.Writer) *Writer { | |
| 36 | w := &Writer{out: out} | |
| 37 | if f, ok := out.(*os.File); ok { | |
| 38 | fd := f.Fd() | |
| 39 | w.isTerminal = isatty.IsTerminal(fd) | |
| 40 | w.fd = int(fd) | |
| 41 | } | |
| 42 | return w | |
| 35 | 43 | } |
| 36 | 44 | |
| 37 | 45 | // Flush flushes the underlying buffer |
| 61 | 69 | } |
| 62 | 70 | |
| 63 | 71 | func (w *Writer) GetWidth() (int, error) { |
| 64 | if f, ok := w.out.(*os.File); ok { | |
| 65 | if isatty.IsTerminal(f.Fd()) { | |
| 66 | tw, _, err := terminal.GetSize(int(f.Fd())) | |
| 67 | return tw, err | |
| 68 | } | |
| 72 | if w.isTerminal { | |
| 73 | tw, _, err := terminal.GetSize(w.fd) | |
| 74 | return tw, err | |
| 69 | 75 | } |
| 70 | 76 | return -1, NotATTY |
| 71 | 77 | } |