这是indexloc提供的服务,不要输入任何密码
Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 25 additions & 8 deletions progress.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ var Out = os.Stdout
var RefreshInterval = time.Millisecond * 10

// defaultProgress is the default progress
var defaultProgress = New()
var defaultProgress *Progress

// Progress represents the container that renders progress bars
type Progress struct {
Expand Down Expand Up @@ -54,21 +54,32 @@ func New() *Progress {

// AddBar creates a new progress bar and adds it to the default progress container
func AddBar(total int) *Bar {
if defaultProgress == nil {
defaultProgress = New()
}
return defaultProgress.AddBar(total)
}

// Start starts the rendering the progress of progress bars using the DefaultProgress. It listens for updates using `bar.Set(n)` and new bars when added using `AddBar`
func Start() {
if defaultProgress == nil {
defaultProgress = New()
}
defaultProgress.Start()
}

// Stop stops listening
func Stop() {
defaultProgress.Stop()
if defaultProgress != nil {
defaultProgress.Stop()
}
}

// Listen listens for updates and renders the progress bars
func Listen() {
if defaultProgress == nil {
defaultProgress = New()
}
defaultProgress.Listen()
}

Expand All @@ -83,6 +94,16 @@ func (p *Progress) AddBar(total int) *Bar {
return bar
}

func (p *Progress) renderBars() {
p.mtx.RLock()
for _, bar := range p.Bars {
fmt.Fprintln(p.lw, bar.String())
}
p.lw.Flush()
p.mtx.RUnlock()

}

// Listen listens for updates and renders the progress bars
func (p *Progress) Listen() {
p.lw.Out = p.Out
Expand All @@ -92,12 +113,7 @@ func (p *Progress) Listen() {
return
default:
time.Sleep(p.RefreshInterval)
p.mtx.RLock()
for _, bar := range p.Bars {
fmt.Fprintln(p.lw, bar.String())
}
p.lw.Flush()
p.mtx.RUnlock()
p.renderBars()
}
}
}
Expand All @@ -114,6 +130,7 @@ func (p *Progress) Start() {
func (p *Progress) Stop() {
close(p.stopChan)
p.stopChan = nil
p.renderBars()
}

// Bypass returns a writer which allows non-buffered data to be written to the underlying output
Expand Down