diff options
Diffstat (limited to 'internal/tui')
| -rw-r--r-- | internal/tui/tui.go | 15 | ||||
| -rw-r--r-- | internal/tui/tui_test.go | 22 |
2 files changed, 37 insertions, 0 deletions
diff --git a/internal/tui/tui.go b/internal/tui/tui.go index c9f1241..e7872c8 100644 --- a/internal/tui/tui.go +++ b/internal/tui/tui.go @@ -36,6 +36,21 @@ func Colour(w io.Writer) bool { return !noColour } +// Width is the terminal's column count, 0 when w is not a terminal or the +// size cannot be read: callers wrap text to it, and treat 0 as "never +// wrap", which keeps output piped to a file one field per line. +func Width(w io.Writer) int { + f, ok := w.(*os.File) + if !ok || !isTerminal(int(f.Fd())) { + return 0 + } + cols, _, err := termSize(int(f.Fd())) + if err != nil { + return 0 + } + return cols +} + // height is the terminal's row count, 0 when it is not a terminal or the // size cannot be read. func height(w io.Writer) int { diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go index a3640ac..614f239 100644 --- a/internal/tui/tui_test.go +++ b/internal/tui/tui_test.go @@ -51,6 +51,28 @@ func TestHeight(t *testing.T) { } } +// TestWidth: the terminal's column count, and 0 wherever there is no +// terminal to wrap to, so a caller treats 0 as "never wrap". +func TestWidth(t *testing.T) { + var buf bytes.Buffer + if w := Width(&buf); w != 0 { + t.Errorf("Width on a non-terminal writer = %d, want 0", w) + } + + oldT, oldS := isTerminal, termSize + t.Cleanup(func() { isTerminal, termSize = oldT, oldS }) + isTerminal = func(fd int) bool { return true } + termSize = func(fd int) (int, int, error) { return 132, 24, nil } + if w := Width(os.Stdout); w != 132 { + t.Errorf("Width = %d, want 132", w) + } + + termSize = func(fd int) (int, int, error) { return 0, 0, os.ErrInvalid } + if w := Width(os.Stdout); w != 0 { + t.Errorf("Width when the size cannot be read = %d, want 0", w) + } +} + func TestPageUsesPagerOnlyWhenTaller(t *testing.T) { dir := t.TempDir() marker := filepath.Join(dir, "paged") |
