2021-03-15 17:30:18 +00:00
|
|
|
package output
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"go.uber.org/atomic"
|
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
var spinner = []string{"⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"}
|
|
|
|
|
|
|
|
const (
|
|
|
|
progressTimeout = 10 * time.Second
|
|
|
|
progressRefreshRate = 200 * time.Millisecond
|
|
|
|
)
|
|
|
|
|
|
|
|
type Progress interface {
|
|
|
|
Start()
|
|
|
|
Stop()
|
|
|
|
Inc()
|
|
|
|
Val() uint64
|
|
|
|
}
|
|
|
|
|
|
|
|
type progress struct {
|
|
|
|
endChan chan struct{}
|
|
|
|
started *atomic.Bool
|
|
|
|
count *atomic.Uint64
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewProgress() *progress {
|
|
|
|
return &progress{
|
2021-03-16 17:07:22 +00:00
|
|
|
nil,
|
2021-03-15 17:30:18 +00:00
|
|
|
atomic.NewBool(false),
|
|
|
|
atomic.NewUint64(0),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *progress) Start() {
|
|
|
|
if !p.started.Swap(true) {
|
2021-03-16 17:07:22 +00:00
|
|
|
p.count.Store(0)
|
|
|
|
p.endChan = make(chan struct{})
|
2021-03-15 17:30:18 +00:00
|
|
|
go p.watch()
|
|
|
|
go p.render()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *progress) Stop() {
|
|
|
|
if p.started.Swap(false) {
|
2021-03-26 20:03:44 +00:00
|
|
|
Printf("Scanned resources: (%d)\n", p.count.Load())
|
2021-03-16 17:07:22 +00:00
|
|
|
close(p.endChan)
|
2021-03-15 17:30:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *progress) Inc() {
|
|
|
|
if p.started.Load() {
|
2021-03-16 17:07:22 +00:00
|
|
|
p.count.Inc()
|
2021-03-15 17:30:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *progress) Val() uint64 {
|
|
|
|
return p.count.Load()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *progress) render() {
|
|
|
|
i := -1
|
|
|
|
Printf("Scanning resources:\r")
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-p.endChan:
|
|
|
|
return
|
|
|
|
case <-time.After(progressRefreshRate):
|
|
|
|
i++
|
|
|
|
if i >= len(spinner) {
|
|
|
|
i = 0
|
|
|
|
}
|
|
|
|
Printf("Scanning resources: %s (%d)\r", spinner[i], p.count.Load())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *progress) watch() {
|
|
|
|
Loop:
|
|
|
|
for {
|
2021-03-16 17:07:22 +00:00
|
|
|
lastVal := p.count.Load()
|
2021-03-15 17:30:18 +00:00
|
|
|
select {
|
|
|
|
case <-time.After(progressTimeout):
|
2021-03-16 17:07:22 +00:00
|
|
|
if p.count.Load() != lastVal {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if p.started.Swap(false) {
|
|
|
|
close(p.endChan)
|
|
|
|
break Loop
|
|
|
|
}
|
2021-03-15 17:30:18 +00:00
|
|
|
case <-p.endChan:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
logrus.Debug("Progress did not receive any tic. Stopping...")
|
|
|
|
}
|