Skip to content

Commit 488eac7

Browse files
committed
👔 up: x/termenv - fix GetTermSize error, add support from ENV get width and height
1 parent 6d02a84 commit 488eac7

File tree

4 files changed

+31
-6
lines changed

4 files changed

+31
-6
lines changed

x/termenv/detect_nonwin.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,6 @@ func detectSpecialTermColor(termVal string) (ColorLevel, bool) {
4141
return TermColor16, false
4242
}
4343

44-
func syscallStdinFd() int {
45-
return syscall.Stdin
46-
}
44+
func syscallStdinFd() int { return syscall.Stdin }
45+
46+
func syscallStdoutFd() int { return syscall.Stdout }

x/termenv/detect_windows.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,3 +169,8 @@ func EnableVTProcessing(stream syscall.Handle, enable bool) error {
169169
func syscallStdinFd() int {
170170
return int(syscall.Stdin)
171171
}
172+
173+
// on Windows, must convert to int
174+
func syscallStdoutFd() int {
175+
return int(syscall.Stdout)
176+
}

x/termenv/termenv.go

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package termenv
55
import (
66
"fmt"
77
"os"
8+
"strconv"
89

910
"golang.org/x/term"
1011
)
@@ -60,20 +61,37 @@ func setLastErr(err error) {
6061
// )
6162
var terminalWidth, terminalHeight int
6263

63-
// GetTermSize for current console terminal.
64+
// GetTermSize for current console terminal. will first try to get from environment variables COLUMNS and LINES.
6465
func GetTermSize(refresh ...bool) (w int, h int) {
65-
if terminalWidth > 0 && len(refresh) > 0 && !refresh[0] {
66+
if terminalWidth > 0 && (len(refresh) == 0 || !refresh[0]) {
67+
return terminalWidth, terminalHeight
68+
}
69+
70+
// 首先尝试从环境变量获取
71+
if cols := os.Getenv("COLUMNS"); cols != "" {
72+
if width, err := strconv.Atoi(cols); err == nil && width > 0 {
73+
terminalWidth = width
74+
}
75+
}
76+
if rows := os.Getenv("LINES"); rows != "" {
77+
if height, err := strconv.Atoi(rows); err == nil && height > 0 {
78+
terminalHeight = height
79+
}
80+
}
81+
if terminalWidth > 0 && terminalHeight > 0 {
6682
return terminalWidth, terminalHeight
6783
}
6884

6985
var err error
70-
w, h, err = term.GetSize(syscallStdinFd())
86+
w, h, err = term.GetSize(syscallStdoutFd())
7187
if err != nil {
88+
debugf("get terminal size error: %v", err)
7289
return
7390
}
7491

7592
// cache result
7693
terminalWidth, terminalHeight = w, h
94+
debugf("get terminal size: %d,%d", w, h)
7795
return
7896
}
7997

x/termenv/util_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import (
88
)
99

1010
func TestCurrentShell(t *testing.T) {
11+
assert.NotNil(t, termenv.IsTerminal())
12+
1113
path := termenv.CurrentShell(true)
1214

1315
if path != "" {

0 commit comments

Comments
 (0)