progress.go 1.41 KB
Newer Older
Michael Yang's avatar
Michael Yang committed
1
2
3
4
5
package progress

import (
	"fmt"
	"io"
Michael Yang's avatar
Michael Yang committed
6
7
	"os"
	"strings"
Michael Yang's avatar
Michael Yang committed
8
9
	"sync"
	"time"
Michael Yang's avatar
Michael Yang committed
10
11

	"golang.org/x/term"
Michael Yang's avatar
Michael Yang committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
)

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 {
	p := &Progress{pos: -1, w: w}
	go p.start()
	return p
}

Michael Yang's avatar
Michael Yang committed
33
func (p *Progress) Stop() bool {
Michael Yang's avatar
Michael Yang committed
34
35
36
37
	if p.ticker != nil {
		p.ticker.Stop()
		p.ticker = nil
		p.render()
Michael Yang's avatar
Michael Yang committed
38
		return true
Michael Yang's avatar
Michael Yang committed
39
	}
Michael Yang's avatar
Michael Yang committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

	return false
}

func (p *Progress) StopAndClear() bool {
	stopped := p.Stop()
	if stopped {
		termWidth, _, err := term.GetSize(int(os.Stderr.Fd()))
		if err != nil {
			panic(err)
		}

		// clear the progress bar by:
		// 1. reset to beginning of line
		// 2. move up to the first line of the progress bar
		// 3. fill the terminal width with spaces
		// 4. reset to beginning of line
		fmt.Fprintf(p.w, "\r\033[%dA%s\r", p.pos, strings.Repeat(" ", termWidth))
	}

	return stopped
Michael Yang's avatar
Michael Yang committed
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
}

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()

	fmt.Fprintf(p.w, "\033[%dA", p.pos)
	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()
	}
}