Skip to content

Commit 1a5d483

Browse files
authored
Merge pull request #215 from WGH-/fix-termWidth
Fix terminal width when stdout is redirected
2 parents d367bcc + 40eb747 commit 1a5d483

File tree

2 files changed

+10
-7
lines changed

2 files changed

+10
-7
lines changed

progressbar.go

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1192,7 +1192,7 @@ func renderProgressBar(c config, s *state) (int, error) {
11921192
}
11931193

11941194
if c.fullWidth && !c.ignoreLength {
1195-
width, err := termWidth()
1195+
width, err := termWidth(c.writer)
11961196
if err != nil {
11971197
width = 80
11981198
}
@@ -1480,12 +1480,15 @@ func logn(n, b float64) float64 {
14801480

14811481
// termWidth function returns the visible width of the current terminal
14821482
// and can be redefined for testing
1483-
var termWidth = func() (width int, err error) {
1484-
width, _, err = term.GetSize(int(os.Stdout.Fd()))
1485-
if err == nil {
1486-
return width, nil
1483+
var termWidth = func(w io.Writer) (width int, err error) {
1484+
if f, ok := w.(*os.File); ok {
1485+
width, _, err = term.GetSize(int(f.Fd()))
1486+
if err == nil {
1487+
return width, nil
1488+
}
1489+
} else {
1490+
err = errors.New("output is not a *os.File")
14871491
}
1488-
14891492
return 0, err
14901493
}
14911494

progressbar_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import (
2222
)
2323

2424
func TestMain(m *testing.M) {
25-
termWidth = func() (int, error) {
25+
termWidth = func(w io.Writer) (int, error) {
2626
return 0, os.ErrPermission
2727
}
2828
os.Exit(m.Run())

0 commit comments

Comments
 (0)