mpb package - github.com/vbauerster/mpb/v8 - Go Packages (original) (raw)

Package mpb is a library for rendering progress bars in terminal applications.

// initialize progress container, with custom width p := mpb.New(mpb.WithWidth(64))

total := 100 name := "Single Bar:" // create a single bar, which will inherit container's width bar := p.New(int64(total), // BarFillerBuilder with custom style mpb.BarStyle().Lbound("╢").Filler("▌").Tip("▌").Padding("░").Rbound("╟"), mpb.PrependDecorators( // display our name with one space on the right decor.Name(name, decor.WC{C: decor.DindentRight | decor.DextraSpace}), // replace ETA decorator with "done" message, OnComplete event decor.OnComplete(decor.AverageETA(decor.ET_STYLE_GO), "done"), ), mpb.AppendDecorators(decor.Percentage()), ) // simulating some work max := 100 * time.Millisecond for i := 0; i < total; i++ { time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10) bar.Increment() } // wait for our bar to complete and flush p.Wait()

This section is empty.

ErrDone represents use after `(*Progress).Wait()` error.

This section is empty.

Bar represents a progress bar.

func (b *Bar) Abort(drop bool)

Abort interrupts bar's running goroutine. Abort won't be engaged if bar is already in complete state. If drop is true bar will be removed as well. To make sure that bar has been removed call `(*Bar).Wait()` method.

func (b *Bar) Aborted() bool

Aborted reports whether the bar is in aborted state.

func (b *Bar) Completed() bool

Completed reports whether the bar is in completed state.

p := mpb.New() bar := p.AddBar(100)

max := 100 * time.Millisecond for !bar.Completed() { time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10) bar.Increment() }

p.Wait()

Current returns bar's current value, in other words sum of all increments.

func (b *Bar) DecoratorAverageAdjust(start time.Time)

DecoratorAverageAdjust adjusts decorators implementing decor.AverageDecorator interface. Call if there is need to set start time after decorators have been constructed.

func (b *Bar) EnableTriggerComplete()

EnableTriggerComplete enables triggering complete event. It's effective only for bars which were constructed with `total <= 0`. If `current >= total` at the moment of call, complete event is triggered right away.

func (*Bar) EwmaIncrBy added in v8.1.0

EwmaIncrBy is a shorthand for b.EwmaIncrInt64(int64(n), iterDur).

func (*Bar) EwmaIncrInt64 added in v8.1.0

EwmaIncrInt64 increments progress by amount of n and updates EWMA based decorators by dur of a single iteration.

func (*Bar) EwmaIncrement added in v8.1.0

EwmaIncrement is a shorthand for b.EwmaIncrInt64(1, iterDur).

EwmaSetCurrent sets progress' current to an arbitrary value and updates EWMA based decorators by dur of a single iteration.

ID returns id of the bar.

func (b *Bar) IncrBy(n int)

IncrBy is a shorthand for b.IncrInt64(int64(n)).

func (b *Bar) IncrInt64(n int64)

IncrInt64 increments progress by amount of n.

func (b *Bar) Increment()

Increment is a shorthand for b.IncrInt64(1).

func (b *Bar) IsRunning() bool

IsRunning reports whether the bar is in running state.

ProxyReader wraps io.Reader with metrics required for progress tracking. If `r` is 'unknown total/size' reader it's mandatory to call `(*Bar).SetTotal(-1, true)` after the wrapper returns `io.EOF`. If bar is already completed or aborted, returns nil. Panics if `r` is nil.

// import crand "crypto/rand"

var total int64 = 1024 * 1024 * 500 reader := io.LimitReader(crand.Reader, total)

p := mpb.New() bar := p.AddBar(total, mpb.AppendDecorators( decor.CountersKibiByte("% .2f / % .2f"), ), )

// create proxy reader proxyReader := bar.ProxyReader(reader) defer func() { _ = proxyReader.Close() }()

// and copy from reader, ignoring errors _, _ = io.Copy(io.Discard, proxyReader)

p.Wait()

ProxyWriter wraps io.Writer with metrics required for progress tracking. If bar is already completed or aborted, returns nil. Panics if `w` is nil.

func (b *Bar) SetCurrent(current int64)

SetCurrent sets progress' current to an arbitrary value.

func (b *Bar) SetPriority(priority int)

SetPriority changes bar's order among multiple bars. Zero is highest priority, i.e. bar will be on top. If you don't need to set priority dynamically, better use BarPriority option.

func (b *Bar) SetRefill(amount int64)

SetRefill sets refill flag with specified amount. The underlying BarFiller will change its visual representation, to indicate refill event. Refill event may be referred to some retry operation for example.

func (b *Bar) SetTotal(total int64, complete bool)

SetTotal sets total to an arbitrary value. It's effective only for bar which was constructed with `total <= 0`. Setting total to negative value is equivalent to `(*Bar).SetTotal((*Bar).Current(), bool)` but faster. If `complete` is true complete event is triggered right away. Calling `(*Bar).EnableTriggerComplete` makes this one no operational.

TraverseDecorators traverses available decorators and calls `cb` on each unwrapped one.

Wait blocks until bar is completed or aborted.

BarFiller interface. Bar (without decorators) renders itself by calling BarFiller's Fill method.

type BarFillerBuilder interface { Build() BarFiller }

BarFillerBuilder interface. Default implementations are:

BarStyle() SpinnerStyle() NopStyle()

func NopStyle() BarFillerBuilder

NopStyle provides BarFillerBuilder which builds NOP BarFiller.

BarFillerFunc is function type adapter to convert compatible function into BarFiller interface.

type BarOption func(*bState)

BarOption is a func option to alter default behavior of a bar.

AppendDecorators let you inject decorators to the bar's right side.

func BarExtender(filler BarFiller, rev bool) BarOption

BarExtender extends bar with arbitrary lines. Provided BarFiller will be called at each render/flush cycle. Any lines written to the underlying io.Writer will extend the bar either in above (rev = true) or below (rev = false) direction.

func BarFillerClearOnAbort() BarOption

BarFillerClearOnAbort clears bar's filler on abort event. It's shortcut for BarFillerOnAbort("").

func BarFillerClearOnComplete() BarOption

BarFillerClearOnComplete clears bar's filler on complete event. It's shortcut for BarFillerOnComplete("").

func BarFillerMiddleware(middle func(BarFiller) BarFiller) BarOption

BarFillerMiddleware provides a way to augment the underlying BarFiller.

func BarFillerOnAbort(message string) BarOption

BarFillerOnAbort replaces bar's filler with message, on abort event.

func BarFillerOnComplete(message string) BarOption

BarFillerOnComplete replaces bar's filler with message, on complete event.

func BarFillerTrim() BarOption

BarFillerTrim removes leading and trailing space around the underlying BarFiller.

func BarFuncOptOn(option func() BarOption, predicate func() bool) BarOption

BarFuncOptOn will call option and return its value only when predicate evaluates to true.

func BarFuncOptional(option func() BarOption, cond bool) BarOption

BarFuncOptional will call option and return its value only when cond is true.

func BarNoPop() BarOption

BarNoPop disables bar pop out of container. Effective when PopCompletedMode of container is enabled.

func BarOptOn(option BarOption, predicate func() bool) BarOption

BarOptOn will return provided option only when predicate evaluates to true.

func BarOptional(option BarOption, cond bool) BarOption

BarOptional will return provided option only when cond is true.

func BarPriority(priority int) BarOption

BarPriority sets bar's priority. Zero is highest priority, i.e. bar will be on top. This option isn't effective with `BarQueueAfter` option.

func BarQueueAfter(bar *Bar) BarOption

BarQueueAfter puts this (being constructed) bar into the queue. BarPriority will be inherited from the argument bar. When argument bar completes or aborts queued bar replaces its place.

func BarRemoveOnComplete() BarOption

BarRemoveOnComplete removes both bar's filler and its decorators on complete event.

func BarWidth(width int) BarOption

BarWidth sets bar width independent of the container.

PrependDecorators let you inject decorators to the bar's left side.

BarStyleComposer interface.

func BarStyle() BarStyleComposer

BarStyle constructs default bar style which can be altered via BarStyleComposer interface.

type ContainerOption func(*pState)

ContainerOption is a func option to alter default behavior of a bar container. Container term refers to a Progress struct which can hold one or more Bars.

func ContainerFuncOptOn(option func() ContainerOption, predicate func() bool) ContainerOption

ContainerFuncOptOn will call option and return its value only when predicate evaluates to true.

func ContainerFuncOptional(option func() ContainerOption, cond bool) ContainerOption

ContainerFuncOptional will call option and return its value only when cond is true.

func ContainerOptOn(option ContainerOption, predicate func() bool) ContainerOption

ContainerOptOn will return provided option only when predicate evaluates to true.

func ContainerOptional(option ContainerOption, cond bool) ContainerOption

ContainerOptional will return provided option only when cond is true.

func PopCompletedMode() ContainerOption

PopCompletedMode pop completed bars out of progress container. In this mode completed bars get moved to the top and stop participating in rendering cycle.

func WithAutoRefresh() ContainerOption

WithAutoRefresh force auto refresh regardless of what output is set to. Applicable only if not WithManualRefresh set.

WithDebugOutput sets debug output.

func WithManualRefresh(ch <-chan interface{}) ContainerOption

WithManualRefresh disables internal auto refresh time.Ticker. Refresh will occur upon receive value from provided ch.

WithOutput overrides default os.Stdout output. If underlying io.Writer is not a terminal then auto refresh is disabled unless WithAutoRefresh option is set.

func WithQueueLen(len int) ContainerOption

WithQueueLen sets buffer size of heap manager channel. Ideally it must be kept at MAX value, where MAX is number of bars to be rendered at the same time. Default queue len is 128.

WithRefreshRate overrides default 150ms refresh rate.

func WithRenderDelay(ch <-chan struct{}) ContainerOption

WithRenderDelay delays rendering. By default rendering starts as soon as bar is added, with this option it's possible to delay rendering process by keeping provided chan unclosed. In other words rendering will start as soon as provided chan is closed.

func WithShutdownNotifier(ch chan<- interface{}) ContainerOption

WithShutdownNotifier value of type `[]*mpb.Bar` will be send to provided channel on shutdown event, i.e. after `(*Progress) Wait()` or `(*Progress) Shutdown()` call.

WithWaitGroup provides means to have a single joint point. If *sync.WaitGroup is provided, you can safely call just p.Wait() without calling Wait() on provided *sync.WaitGroup. Makes sense when there are more than one bar to render.

func WithWidth(width int) ContainerOption

WithWidth sets container width. If not set it defaults to terminal width. A bar added to the container will inherit its width, unless overridden by `func BarWidth(int) BarOption`.

Progress represents a container that renders one or more progress bars.

func New(options ...ContainerOption) *Progress

New creates new Progress container instance. It's not possible to reuse instance after `(*Progress).Wait` method has been called.

NewWithContext creates new Progress container instance with provided context. It's not possible to reuse instance after `(*Progress).Wait` method has been called.

Add creates a bar which renders itself by provided BarFiller. If `total <= 0` triggering complete event by increment methods is disabled. If called after `(*Progress).Wait()` then `(nil, ErrDone)` is returned.

func (p *Progress) AddBar(total int64, options ...BarOption) *Bar

AddBar creates a bar with default bar filler.

func (p *Progress) AddSpinner(total int64, options ...BarOption) *Bar

AddSpinner creates a bar with default spinner filler.

func (p *Progress) MustAdd(total int64, filler BarFiller, options ...BarOption) *Bar

MustAdd creates a bar which renders itself by provided BarFiller. If `total <= 0` triggering complete event by increment methods is disabled. Panics if called after `(*Progress).Wait()`.

func (p *Progress) New(total int64, builder BarFillerBuilder, options ...BarOption) *Bar

New creates a bar by calling `Build` method on provided `BarFillerBuilder`.

func (p *Progress) Shutdown()

Shutdown cancels any running bar immediately and then shutdowns `*Progress` instance. Normally this method shouldn't be called unless you know what you are doing. Proper way to shutdown is to call `(*Progress).Wait()` instead.

func (p *Progress) UpdateBarPriority(b *Bar, priority int, lazy bool)

UpdateBarPriority either immediately or lazy. With lazy flag order is updated after the next refresh cycle. If you don't care about laziness just use `(*Bar).SetPriority(int)`.

func (p *Progress) Wait()

Wait waits for all bars to complete and finally shutdowns container. After this method has been called, there is no way to reuse `*Progress` instance.

Write is implementation of io.Writer. Writing to `*Progress` will print lines above a running bar. Writes aren't flushed immediately, but at next refresh cycle. If called after `(*Progress).Wait()` then `(0, ErrDone)` is returned.

type SpinnerStyleComposer interface { BarFillerBuilder PositionLeft() SpinnerStyleComposer PositionRight() SpinnerStyleComposer Meta(func(string) string) SpinnerStyleComposer }

SpinnerStyleComposer interface.

SpinnerStyle constructs default spinner style which can be altered via SpinnerStyleComposer interface.