From 3adf1a97820f2fba52698006348cdbac24c3c228 Mon Sep 17 00:00:00 2001 From: Michael Vogt Date: Thu, 12 Dec 2024 19:45:44 +0100 Subject: [PATCH] progress: auto-select progress based on $PS1 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 PS1 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. --- bib/internal/progress/progress.go | 11 ++++++++--- bib/internal/progress/progress_test.go | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/bib/internal/progress/progress.go b/bib/internal/progress/progress.go index 3e7bf4ce..e0b1fec6 100644 --- a/bib/internal/progress/progress.go +++ b/bib/internal/progress/progress.go @@ -69,9 +69,14 @@ type ProgressBar interface { // 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 + // shell, use plain progress for scripts + if _, ok := os.LookupEnv("PS1"); ok { + return NewTerminalProgressBar() + } + return NewPlainProgressBar() + case "plain": return NewPlainProgressBar() case "term": return NewTerminalProgressBar() diff --git a/bib/internal/progress/progress_test.go b/bib/internal/progress/progress_test.go index 6b11d6f6..ea85ea01 100644 --- a/bib/internal/progress/progress_test.go +++ b/bib/internal/progress/progress_test.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "reflect" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -111,3 +112,23 @@ 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{}}, + {"PS1=foo", &progress.TerminalProgressBar{}}, + } { + + 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)) + } + +}