Skip to content

Commit

Permalink
Merge pull request #88 from trntv/master
Browse files Browse the repository at this point in the history
Pre- and Post- update functions
  • Loading branch information
briandowns authored Feb 15, 2020
2 parents 3c88530 + 08975ec commit 6dc2240
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
12 changes: 11 additions & 1 deletion spinner.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ type Spinner struct {
active bool // active holds the state of the spinner
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
PostUpdate func(s *Spinner) // will be triggered after every spinner update
}

// New provides a pointer to an instance of Spinner with the supplied options
Expand Down Expand Up @@ -278,6 +280,10 @@ func (s *Spinner) Start() {
return
}

if s.PreUpdate != nil {
s.PreUpdate(s)
}

var outColor string
if runtime.GOOS == "windows" {
if s.Writer == os.Stderr {
Expand All @@ -292,8 +298,12 @@ func (s *Spinner) Start() {
fmt.Fprint(s.Writer, outColor)
s.lastOutput = outPlain
delay := s.Delay
s.lock.Unlock()

if s.PostUpdate != nil {
s.PostUpdate(s)
}

s.lock.Unlock()
time.Sleep(delay)
}
}
Expand Down
30 changes: 30 additions & 0 deletions spinner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,36 @@ func TestRestart(t *testing.T) {
s = nil
}

// TestHookFunctions will verify that hook functions works as expected
func TestHookFunctions(t *testing.T) {
s := New(CharSets[4], 50*time.Millisecond)
var out syncBuffer
s.Writer = &out
s.PreUpdate = func(s *Spinner) {
fmt.Fprintf(s.Writer, "pre-update")
}
s.PostUpdate = func(s *Spinner) {
fmt.Fprintf(s.Writer, "post-update")
}

s.Start()
s.Color("cyan")
time.Sleep(200 * time.Millisecond)
s.Stop()
time.Sleep(50 * time.Millisecond)
out.Lock()
defer out.Unlock()
result := out.Bytes()
if !bytes.Contains(result, []byte("pre-update")) {
t.Error("pre-update failed")
}

if !bytes.Contains(result, []byte("post-update")) {
t.Error("post-update failed")
}
s = nil
}

// TestReverse will verify that the given spinner can stop and start again reversed
func TestReverse(t *testing.T) {
a := New(CharSets[10], 1*time.Second)
Expand Down

0 comments on commit 6dc2240

Please sign in to comment.