From 329c376a7599eac4c02412b50b8325beeaf79fc1 Mon Sep 17 00:00:00 2001 From: Jaroslav Holub Date: Sun, 31 Jul 2022 05:37:46 +0200 Subject: [PATCH] add enable/disable toggle (#144) --- spinner.go | 21 ++++++++++++++++++++- spinner_test.go | 22 ++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/spinner.go b/spinner.go index 3268f06..b8abe6a 100644 --- a/spinner.go +++ b/spinner.go @@ -186,6 +186,7 @@ type Spinner struct { color func(a ...interface{}) string // default color is white Writer io.Writer // to make testing better, exported so users have access. Use `WithWriter` to update after initialization. active bool // active holds the state of the spinner + enabled bool // indicates whether the spinner is enabled or not stopChan chan struct{} // stopChan is a channel used to stop the indicator HideCursor bool // hideCursor determines if the cursor is visible PreUpdate func(s *Spinner) // will be triggered before every spinner update @@ -202,6 +203,7 @@ func New(cs []string, d time.Duration, options ...Option) *Spinner { Writer: color.Output, stopChan: make(chan struct{}, 1), active: false, + enabled: true, HideCursor: true, } @@ -271,10 +273,27 @@ func (s *Spinner) Active() bool { return s.active } +// Enabled returns whether or not the spinner is enabled. +func (s *Spinner) Enabled() bool { + return s.enabled +} + +// Enable enables and restarts the spinner +func (s *Spinner) Enable() { + s.enabled = true + s.Restart() +} + +// Disable stops and disables the spinner +func (s *Spinner) Disable() { + s.enabled = false + s.Stop() +} + // Start will start the indicator. func (s *Spinner) Start() { s.mu.Lock() - if s.active || !isRunningInTerminal() { + if s.active || !s.enabled || !isRunningInTerminal() { s.mu.Unlock() return } diff --git a/spinner_test.go b/spinner_test.go index 8ddf092..3d66848 100644 --- a/spinner_test.go +++ b/spinner_test.go @@ -132,6 +132,28 @@ func TestRestart(t *testing.T) { } } +func TestDisable(t *testing.T) { + s, _ := withOutput(CharSets[4], 100*time.Millisecond) + + s.Start() + time.Sleep(150 * time.Millisecond) + if !s.Enabled() { + t.Error("expected enabled spinner after startup") + } + time.Sleep(150 * time.Millisecond) + s.Disable() + time.Sleep(150 * time.Millisecond) + if s.Enabled() { + t.Error("expected disabling the spinner works") + } + time.Sleep(150 * time.Millisecond) + s.Enable() + time.Sleep(150 * time.Millisecond) + if !s.Enabled() { + t.Error("expected enabling the spinner works") + } +} + // TestHookFunctions will verify that hook functions works as expected func TestHookFunctions(t *testing.T) { if !isatty.IsTerminal(os.Stdout.Fd()) {