consolidate checks whether stdin/stdout is terminal

This commit is contained in:
Michael Eischer
2025-09-07 14:19:29 +02:00
parent 93ccc548c8
commit 0b0dd07f15
8 changed files with 54 additions and 43 deletions

View File

@@ -0,0 +1,29 @@
package terminal
import (
"os"
"golang.org/x/term"
)
func StdinIsTerminal() bool {
return term.IsTerminal(int(os.Stdin.Fd()))
}
func StdoutIsTerminal() bool {
// mintty on windows can use pipes which behave like a posix terminal,
// but which are not a terminal handle
return term.IsTerminal(int(os.Stdout.Fd())) || StdoutCanUpdateStatus()
}
func StdoutCanUpdateStatus() bool {
return CanUpdateStatus(os.Stdout.Fd())
}
func StdoutTerminalWidth() int {
w, _, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
return 0
}
return w
}

View File

@@ -13,7 +13,7 @@ const (
PosixControlClearLine = "\x1b[2K"
)
// posixClearCurrentLine removes all characters from the current line and resets the
// PosixClearCurrentLine removes all characters from the current line and resets the
// cursor position to the first column.
func PosixClearCurrentLine(wr io.Writer, _ uintptr) {
// clear current line
@@ -24,7 +24,7 @@ func PosixClearCurrentLine(wr io.Writer, _ uintptr) {
}
}
// posixMoveCursorUp moves the cursor to the line n lines above the current one.
// PosixMoveCursorUp moves the cursor to the line n lines above the current one.
func PosixMoveCursorUp(wr io.Writer, _ uintptr, n int) {
data := []byte(PosixControlMoveCursorHome)
data = append(data, bytes.Repeat([]byte(PosixControlMoveCursorUp), n)...)

View File

@@ -10,13 +10,13 @@ import (
"golang.org/x/term"
)
// clearCurrentLine removes all characters from the current line and resets the
// ClearCurrentLine removes all characters from the current line and resets the
// cursor position to the first column.
func ClearCurrentLine(_ uintptr) func(io.Writer, uintptr) {
return PosixClearCurrentLine
}
// moveCursorUp moves the cursor to the line n lines above the current one.
// MoveCursorUp moves the cursor to the line n lines above the current one.
func MoveCursorUp(_ uintptr) func(io.Writer, uintptr, int) {
return PosixMoveCursorUp
}