Skip to content

Commit

Permalink
refactor: TerminalWidthMin
Browse files Browse the repository at this point in the history
  • Loading branch information
hui.wang committed Jan 27, 2022
1 parent 387888e commit ecd9da2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 29 deletions.
7 changes: 5 additions & 2 deletions xutil/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ func realLength(s string) int {
// TerminalWidthRate 输出时占用的宽度比例
var TerminalWidthRate float32 = 0.9

// TerminalWidthMin 最小终端宽度,当获取的宽度小于等于该值,不再做换行优化
var TerminalWidthMin = 80

// TableFormatLines fotmat return lines
func TableFormatLines(lineAll []string, magic string) []string {
ret := append([]string{}, lineAll...)
Expand All @@ -48,8 +51,8 @@ func TableFormatLines(lineAll []string, magic string) []string {
ret[index] = line
}
}
w, err := Width()
if err != nil {
w, _, err := TermSize()
if err != nil || w <= TerminalWidthMin {
return ret
}
terminalWitdh := int(float32(w) * TerminalWidthRate)
Expand Down
57 changes: 30 additions & 27 deletions xutil/wrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,43 @@ package xutil

import (
"os"
"os/exec"
"strconv"
"strings"
"runtime"
"syscall"
"unsafe"
)

func size() (string, error) {
cmd := exec.Command("stty", "size")
cmd.Stdin = os.Stdin
out, err := cmd.Output()
return string(out), err
type size struct {
rows uint16
cols uint16
}

func parse(input string) (uint, uint, error) {
parts := strings.Split(input, " ")
// TermSize get terminal size
func TermSize() (int, int, error) {

x, err := strconv.Atoi(parts[0])
if err != nil {
return 0, 0, err
}
var sz size
var fd uintptr

y, err := strconv.Atoi(strings.Replace(parts[1], "\n", "", 1))
if err != nil {
return 0, 0, err
if runtime.GOOS == "windows" {
if fh, err := syscall.Open("CONOUT$", syscall.O_RDWR, 0); err != nil {
return int(0), int(0), err
} else {
fd = uintptr(fh)
}
} else {
if fp, err := os.OpenFile("/dev/tty", syscall.O_WRONLY, 0); err != nil {
return int(0), int(0), err
} else {
fd = fp.Fd()
}
}

return uint(x), uint(y), nil
}

// Width returns the width of the terminal.
func Width() (uint, error) {
output, err := size()
if err != nil {
return 0, err
if _, _, err := syscall.Syscall(
syscall.SYS_IOCTL,
fd,
uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(&sz))); err != 0 {
return int(0), int(0), err
}
_, width, err := parse(output)
return width, err

return int(sz.cols), int(sz.rows), nil
}

0 comments on commit ecd9da2

Please sign in to comment.