progress.go 1.46 KB
Newer Older
Michael Yang's avatar
Michael Yang committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package progress

import (
	"fmt"
	"io"
	"sync"
	"time"
)

type State interface {
	String() string
}

type Progress struct {
	mu  sync.Mutex
	pos int
	w   io.Writer

	ticker *time.Ticker
	states []State
}

func NewProgress(w io.Writer) *Progress {
Michael Yang's avatar
Michael Yang committed
24
	p := &Progress{w: w}
Michael Yang's avatar
Michael Yang committed
25
26
27
28
	go p.start()
	return p
}

Michael Yang's avatar
Michael Yang committed
29
func (p *Progress) Stop() bool {
30
31
32
33
34
35
	for _, state := range p.states {
		if spinner, ok := state.(*Spinner); ok {
			spinner.Stop()
		}
	}

Michael Yang's avatar
Michael Yang committed
36
37
38
39
	if p.ticker != nil {
		p.ticker.Stop()
		p.ticker = nil
		p.render()
Michael Yang's avatar
Michael Yang committed
40
		return true
Michael Yang's avatar
Michael Yang committed
41
	}
Michael Yang's avatar
Michael Yang committed
42
43
44
45
46

	return false
}

func (p *Progress) StopAndClear() bool {
Michael Yang's avatar
Michael Yang committed
47
48
49
	fmt.Fprint(p.w, "\033[?25l")
	defer fmt.Fprint(p.w, "\033[?25h")

Michael Yang's avatar
Michael Yang committed
50
51
52
	stopped := p.Stop()
	if stopped {
		// clear the progress bar by:
Michael Yang's avatar
Michael Yang committed
53
54
55
56
57
58
		// 1. for each line in the progress:
		//   a. move the cursor up one line
		//   b. clear the line
		for i := 0; i < p.pos; i++ {
			fmt.Fprint(p.w, "\033[A\033[2K")
		}
Michael Yang's avatar
Michael Yang committed
59
60
61
	}

	return stopped
Michael Yang's avatar
Michael Yang committed
62
63
64
65
66
67
68
69
70
71
72
73
74
}

func (p *Progress) Add(key string, state State) {
	p.mu.Lock()
	defer p.mu.Unlock()

	p.states = append(p.states, state)
}

func (p *Progress) render() error {
	p.mu.Lock()
	defer p.mu.Unlock()

Michael Yang's avatar
Michael Yang committed
75
76
77
	fmt.Fprint(p.w, "\033[?25l")
	defer fmt.Fprint(p.w, "\033[?25h")

Michael Yang's avatar
Michael Yang committed
78
79
80
81
	if p.pos > 0 {
		fmt.Fprintf(p.w, "\033[%dA", p.pos)
	}

Michael Yang's avatar
Michael Yang committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
	for _, state := range p.states {
		fmt.Fprintln(p.w, state.String())
	}

	if len(p.states) > 0 {
		p.pos = len(p.states)
	}

	return nil
}

func (p *Progress) start() {
	p.ticker = time.NewTicker(100 * time.Millisecond)
	for range p.ticker.C {
		p.render()
	}
}