Skip to content

Commit

Permalink
progress: tweak how os.Stderr is mocked
Browse files Browse the repository at this point in the history
This commit changes the way `os.Stderr` is mocked so that higher
level consumes of the libary can use helpers can replace os.Stderr
(like `testutil.CaptureStdio()` is doing). The existing approach
assigns the "real" os.Stderr to osStderr so early that it cannot
be changed later.
  • Loading branch information
mvo5 committed Feb 5, 2025
1 parent db7b418 commit 8d088db
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
2 changes: 1 addition & 1 deletion bib/pkg/progress/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type (

func MockOsStderr(w io.Writer) (restore func()) {
saved := osStderr
osStderr = w
osStderr = func() io.Writer { return w }
return func() {
osStderr = saved
}
Expand Down
15 changes: 10 additions & 5 deletions bib/pkg/progress/progress.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ import (
)

var (
osStderr io.Writer = os.Stderr

// This is only needed because pb.Pool require a real terminal.
// It sets it into "raw-mode" but there is really no need for
// this (see "func render()" below) so once this is fixed
Expand All @@ -30,6 +28,13 @@ var (
CURSOR_SHOW = ESC + "[?25h"
)

// Used for testing, this must be a function (instead of the usual
// "var osStderr = os.Stderr" so that higher level libraries can test
// this code by replacing "os.Stderr", e.g. testutil.CaptureStdio()
var osStderr = func() io.Writer {
return os.Stderr
}

func cursorUp(i int) string {
return fmt.Sprintf("%s[%dA", ESC, i)
}
Expand Down Expand Up @@ -104,7 +109,7 @@ type terminalProgressBar struct {
// most terminals.
func NewTerminalProgressBar() (ProgressBar, error) {
b := &terminalProgressBar{
out: osStderr,
out: osStderr(),
}
b.spinnerPb = pb.New(0)
b.spinnerPb.SetTemplate(`[{{ (cycle . "|" "/" "-" "\\") }}] {{ string . "spinnerMsg" }}`)
Expand Down Expand Up @@ -248,7 +253,7 @@ type verboseProgressBar struct {
// NewVerboseProgressBar starts a new "verbose" progressbar that will just
// prints message but does not show any progress.
func NewVerboseProgressBar() (ProgressBar, error) {
b := &verboseProgressBar{w: osStderr}
b := &verboseProgressBar{w: osStderr()}
return b, nil
}

Expand Down Expand Up @@ -281,7 +286,7 @@ type debugProgressBar struct {
// so "glitches/weird" messages from the lower-layers can be inspected
// easier.
func NewDebugProgressBar() (ProgressBar, error) {
b := &debugProgressBar{w: osStderr}
b := &debugProgressBar{w: osStderr()}
return b, nil
}

Expand Down

0 comments on commit 8d088db

Please sign in to comment.