File: spinner.go

package info (click to toggle)
golang-github-odeke-em-cli-spinner 0.0~git20150423.610063b-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 84 kB
  • ctags: 13
  • sloc: makefile: 6
file content (105 lines) | stat: -rw-r--r-- 1,814 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package spinner

import (
	"fmt"
	"os"
	"time"
)

var symbolList = []string{
	" | ",
	" / ",
	" – ",
	" \\ ",	
}

var symbolMap = map[string]string{
	" ⏳ ": "\033[37m",
	" ⌛ ": "\033[38m",
}

type Spinner struct {
	duration time.Duration
	trigger  interface{}
	sentinel interface{}
	closed   bool
	// sigChan: is the pipe that receives the start and stop
	sigChan chan interface{}
	// waitChan waits till the shutdown has fully propagated
	waitChan chan interface{}
}

func New(freq int64) *Spinner {
	if freq < 1 {
		freq = 10
	}
	sp := Spinner{
		duration: time.Duration(1e9 / freq),
		sentinel: nil,
		// sigChan will be created on .Start()
		sigChan:  nil,
		waitChan: make(chan interface{}),
	}

	sp.trigger = &sp
	return &sp
}

func (s *Spinner) Start() error {
	err := s.spin()
	if err == nil {
		s.sigChan <- s.trigger
	}
	return err
}

func (s *Spinner) Stop() {
	if !s.closed && s.sigChan != nil {
		s.sigChan <- s.sentinel
		close(s.sigChan)
		<-s.waitChan
		s.closed = true
	}
}

func (s *Spinner) Reset() {
	s.Stop()
	s.sigChan = nil
	s.closed = true
}

func (s *Spinner) Duration() time.Duration {
	return s.duration
}

func (s *Spinner) spin() error {
	if s.sigChan != nil { // Already in use
		return fmt.Errorf("already in use")
	}
	s.sigChan = make(chan interface{})
	go func() {
		// Block till the first symbol comes through
		<-s.sigChan

		throttle := time.Tick(s.duration)
		running := true
		for running {
			for _, segment := range symbolList {
				select {
				case in := <-s.sigChan:
					if in == s.sentinel {
						os.Stderr.Sync()
						running = false
						s.waitChan <- s.sentinel
						break
					}
				default:
				}
				// Print it to stderr to avoid symbol getting into piped content
				fmt.Fprintf(os.Stderr, "%s\r", segment)
				<-throttle
			}
		}
	}()
	return nil
}