51 lines
1.4 KiB
Go
51 lines
1.4 KiB
Go
package cobol
|
|
|
|
import (
|
|
"os"
|
|
"strings"
|
|
"unicode"
|
|
|
|
"go.wit.com/log"
|
|
"golang.org/x/term"
|
|
)
|
|
|
|
var WIDTH int = 120
|
|
|
|
// getTerminalWidth returns the width of the active terminal.
|
|
// If the output is not an interactive terminal (e.g., it's being piped to a file
|
|
// or another command), it returns a default width and false.
|
|
func getTerminalWidth() (int, bool) {
|
|
// term.IsTerminal checks if the given file descriptor is connected to a terminal.
|
|
// We use os.Stdout.Fd() to check the standard output.
|
|
if term.IsTerminal(int(os.Stdout.Fd())) {
|
|
var err error
|
|
// term.GetSize returns the dimensions of the given terminal.
|
|
WIDTH, _, err = term.GetSize(int(os.Stdout.Fd()))
|
|
if err != nil {
|
|
// If we can't get the size for some reason, fall back to the default.
|
|
log.Printf("could not get terminal size: %v", err)
|
|
return WIDTH, false
|
|
}
|
|
return WIDTH, true
|
|
}
|
|
|
|
// If it's not a terminal, return the default width.
|
|
return WIDTH, false
|
|
}
|
|
|
|
// like the perl Chomp but with the terminal width
|
|
func TerminalChomp(cut string) string {
|
|
i, _ := getTerminalWidth()
|
|
// log.Info("cobol.TerminalCut() at ", i)
|
|
|
|
// TrimRightFunc removes all trailing runes r from the string s that satisfy f(r).
|
|
// unicode.IsSpace reports whether the rune is a space character.
|
|
cut = strings.TrimRightFunc(cut, unicode.IsSpace)
|
|
|
|
if i >= len(cut) {
|
|
return cut
|
|
} else {
|
|
return log.Sprintf("%s", cut[0:i])
|
|
}
|
|
}
|