Skip to content

Commit

Permalink
progress: auto-select progress based on the environment
Browse files Browse the repository at this point in the history
This commit adds automatic progress bar selection based on the
environment. Ideally we would check for a terminal but with
podman we never have one. So we check for TERM and SSH_CONNECTION
and anf if that is used we assume it's an interactive shell and
give the nice "terminalProgressBar". If that is not set we assuem
we run in a script or CI/CD environment and select plainProgressBar.
  • Loading branch information
mvo5 committed Dec 19, 2024
1 parent 8f3ca27 commit c6c9f84
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
23 changes: 20 additions & 3 deletions bib/internal/progress/progress.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,29 @@ type ProgressBar interface {
Stop()
}

func isTerminal() bool {
// Note that we cannot simply use "isatty()" here because
// "podman run -it" will not give us a full terminal to
// prevent TIOCSTI - this is the next best we can do.
for _, env := range []string{"TERM", "SSH_CONNECTION"} {
if s := os.Getenv(env); s != "" {
return true
}
}
return false
}

// New creates a new progressbar based on the requested type
func New(typ string) (ProgressBar, error) {
switch typ {
// XXX: autoseelct based on PS1 value (i.e. use term in
// interactive shells only?)
case "", "plain":
case "":
// autoselect based on if we are on an interactive
// terminal, use plain progress for scripts
if isTerminal() {
return NewTerminalProgressBar()
}
return NewPlainProgressBar()
case "plain":
return NewPlainProgressBar()
case "term":
return NewTerminalProgressBar()
Expand Down
25 changes: 25 additions & 0 deletions bib/internal/progress/progress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"reflect"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -111,3 +112,27 @@ func TestTermProgress(t *testing.T) {
// check shutdown
assert.Contains(t, buf.String(), progress.CURSOR_SHOW)
}

func TestProgressNewAutoselect(t *testing.T) {
for _, tc := range []struct {
env string
expected interface{}
}{
{"", &progress.PlainProgressBar{}},
{"TERM=vt100", &progress.TerminalProgressBar{}},
{"SSH_CONNECTION=totally", &progress.TerminalProgressBar{}},
} {

t.Setenv("TERM", "")
t.Setenv("SSH_CONNECTION", "")

if l := strings.SplitN(tc.env, "=", 2); len(l) == 2 {
t.Setenv(l[0], l[1])
}

pb, err := progress.New("")
assert.NoError(t, err)
assert.Equal(t, reflect.TypeOf(pb), reflect.TypeOf(tc.expected), fmt.Sprintf("[%v] %T not the expected %T", tc.env, pb, tc.expected))
}

}

0 comments on commit c6c9f84

Please sign in to comment.