diff --git a/progress.go b/progress.go index a93838d..35e9ff0 100644 --- a/progress.go +++ b/progress.go @@ -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 { @@ -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() } @@ -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 @@ -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() } } } @@ -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