Skip to content

Commit

Permalink
Fix TestOptionFullWidth not always working
Browse files Browse the repository at this point in the history
  • Loading branch information
oerlikon committed Nov 20, 2022
1 parent f9d6be8 commit b2ea7ac
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
27 changes: 19 additions & 8 deletions progressbar.go
Expand Up @@ -188,7 +188,7 @@ func OptionEnableColorCodes(colorCodes bool) Option {
}
}

// OptionSetElapsedTime will enable elapsed time. always enabled if OptionSetPredictTime is true.
// OptionSetElapsedTime will enable elapsed time. Always enabled if OptionSetPredictTime is true.
func OptionSetElapsedTime(elapsedTime bool) Option {
return func(p *ProgressBar) {
p.config.elapsedTime = elapsedTime
Expand Down Expand Up @@ -484,12 +484,12 @@ func (p *ProgressBar) Add(num int) error {
return p.Add64(int64(num))
}

// Set wil set the bar to a current number
// Set will set the bar to a current number
func (p *ProgressBar) Set(num int) error {
return p.Set64(int64(num))
}

// Set64 wil set the bar to a current number
// Set64 will set the bar to a current number
func (p *ProgressBar) Set64(num int64) error {
p.lock.Lock()
toAdd := num - int64(p.state.currentBytes)
Expand Down Expand Up @@ -795,12 +795,9 @@ func renderProgressBar(c config, s *state) (int, error) {
}

if c.fullWidth && !c.ignoreLength {
width, _, err := term.GetSize(int(os.Stdout.Fd()))
width, err := termWidth()
if err != nil {
width, _, err = term.GetSize(int(os.Stderr.Fd()))
if err != nil {
width = 80
}
width = 80
}

amend := 1 // an extra space at eol
Expand Down Expand Up @@ -1062,3 +1059,17 @@ func humanizeBytes(s float64) (string, string) {
func logn(n, b float64) float64 {
return math.Log(n) / math.Log(b)
}

// termWidth function returns the visible width of the current terminal
// and can be redefined for testing
var termWidth = func() (width int, err error) {
width, _, err = term.GetSize(int(os.Stdout.Fd()))
if err == nil {
return width, nil
}
width, _, err = term.GetSize(int(os.Stderr.Fd()))
if err == nil {
return width, nil
}
return 0, err
}
7 changes: 7 additions & 0 deletions progressbar_test.go
Expand Up @@ -16,6 +16,13 @@ import (
"github.com/stretchr/testify/assert"
)

func TestMain(m *testing.M) {
termWidth = func() (int, error) {
return 0, os.ErrPermission
}
os.Exit(m.Run())
}

func BenchmarkRender(b *testing.B) {
bar := NewOptions64(100000000,
OptionSetWriter(os.Stderr),
Expand Down

0 comments on commit b2ea7ac

Please sign in to comment.