mpb

package module
v7.5.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2022 License: Unlicense Imports: 16 Imported by: 85

README

Multi Progress Bar

GoDoc Test status Donate with PayPal

mpb is a Go lib for rendering progress bars in terminal applications.

Features

  • Multiple Bars: Multiple progress bars are supported
  • Dynamic Total: Set total while bar is running
  • Dynamic Add/Remove: Dynamically add or remove bars
  • Cancellation: Cancel whole rendering process
  • Predefined Decorators: Elapsed time, ewma based ETA, Percentage, Bytes counter
  • Decorator's width sync: Synchronized decorator's width among multiple bars

Usage

Rendering single bar
package main

import (
    "math/rand"
    "time"

    "github.com/vbauerster/mpb/v7"
    "github.com/vbauerster/mpb/v7/decor"
)

func main() {
    // 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{W: len(name) + 1, C: decor.DidentRight}),
            // replace ETA decorator with "done" message, OnComplete event
            decor.OnComplete(
                decor.AverageETA(decor.ET_STYLE_GO, decor.WC{W: 4}), "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()
}
Rendering multiple bars
    var wg sync.WaitGroup
    // passed wg will be accounted at p.Wait() call
    p := mpb.New(mpb.WithWaitGroup(&wg))
    total, numBars := 100, 3
    wg.Add(numBars)

    for i := 0; i < numBars; i++ {
        name := fmt.Sprintf("Bar#%d:", i)
        bar := p.AddBar(int64(total),
            mpb.PrependDecorators(
                // simple name decorator
                decor.Name(name),
                // decor.DSyncWidth bit enables column width synchronization
                decor.Percentage(decor.WCSyncSpace),
            ),
            mpb.AppendDecorators(
                // replace ETA decorator with "done" message, OnComplete event
                decor.OnComplete(
                    // ETA decorator with ewma age of 60
                    decor.EwmaETA(decor.ET_STYLE_GO, 60, decor.WCSyncWidth), "done",
                ),
            ),
        )
        // simulating some work
        go func() {
            defer wg.Done()
            rng := rand.New(rand.NewSource(time.Now().UnixNano()))
            max := 100 * time.Millisecond
            for i := 0; i < total; i++ {
                // start variable is solely for EWMA calculation
                // EWMA's unit of measure is an iteration's duration
                start := time.Now()
                time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10)
                bar.Increment()
                // we need to call DecoratorEwmaUpdate to fulfill ewma decorator's contract
                bar.DecoratorEwmaUpdate(time.Since(start))
            }
        }()
    }
    // wait for passed wg and for all bars to complete and flush
    p.Wait()
Dynamic total

dynamic total

Complex example

complex

Bytes counters

byte counters

Documentation

Overview

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

Example
// 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{W: len(name) + 1, C: decor.DidentRight}),
		// replace ETA decorator with "done" message, OnComplete event
		decor.OnComplete(
			// ETA decorator with ewma age of 60, and width reservation of 4
			decor.EwmaETA(decor.ET_STYLE_GO, 60, decor.WC{W: 4}), "done",
		),
	),
	mpb.AppendDecorators(decor.Percentage()),
)
// simulating some work
max := 100 * time.Millisecond
for i := 0; i < total; i++ {
	// start variable is solely for EWMA calculation
	// EWMA's unit of measure is an iteration's duration
	start := time.Now()
	time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10)
	bar.Increment()
	// we need to call DecoratorEwmaUpdate to fulfill ewma decorator's contract
	bar.DecoratorEwmaUpdate(time.Since(start))
}
// wait for our bar to complete and flush
p.Wait()
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bar

type Bar struct {
	// contains filtered or unexported fields
}

Bar represents a progress bar.

func (*Bar) Abort

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 (*Bar) Aborted added in v7.4.0

func (b *Bar) Aborted() bool

Aborted reports whether the bar is in aborted state.

func (*Bar) Completed

func (b *Bar) Completed() bool

Completed reports whether the bar is in completed state.

Example
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()
Output:

func (*Bar) Current

func (b *Bar) Current() int64

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

func (*Bar) DecoratorAverageAdjust

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

DecoratorAverageAdjust adjusts all average based decorators. Call if you need to adjust start time of all average based decorators or after progress resume.

func (*Bar) DecoratorEwmaUpdate

func (b *Bar) DecoratorEwmaUpdate(dur time.Duration)

DecoratorEwmaUpdate updates all EWMA based decorators. Should be called on each iteration, because EWMA's unit of measure is an iteration's duration. Panics if called before *Bar.Incr... family methods.

func (*Bar) EnableTriggerComplete added in v7.4.0

func (b *Bar) EnableTriggerComplete()

EnableTriggerComplete enables triggering complete event. It's effective only for bar which was constructed with `total <= 0` and after total has been set with (*Bar).SetTotal(int64, false). If bar has been incremented to the total, complete event is triggered right away.

func (*Bar) ID

func (b *Bar) ID() int

ID returs id of the bar.

func (*Bar) IncrBy

func (b *Bar) IncrBy(n int)

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

func (*Bar) IncrInt64

func (b *Bar) IncrInt64(n int64)

IncrInt64 increments progress by amount of n.

func (*Bar) Increment

func (b *Bar) Increment()

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

func (*Bar) ProxyReader

func (b *Bar) ProxyReader(r io.Reader) io.ReadCloser

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

Example
// 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 proxyReader.Close()

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

p.Wait()
Output:

func (*Bar) SetCurrent

func (b *Bar) SetCurrent(current int64)

SetCurrent sets progress' current to an arbitrary value. Setting a negative value will cause a panic.

func (*Bar) SetPriority

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 (*Bar) SetRefill

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 (*Bar) SetTotal

func (b *Bar) SetTotal(total int64, triggerCompleteNow 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). If triggerCompleteNow is true, total value is set to current and complete event is triggered right away.

func (*Bar) TraverseDecorators

func (b *Bar) TraverseDecorators(cb func(decor.Decorator))

TraverseDecorators traverses all available decorators and calls cb func on each.

func (*Bar) Wait added in v7.4.0

func (b *Bar) Wait()

Wait blocks until bar is completed or aborted.

type BarFiller

type BarFiller interface {
	Fill(w io.Writer, reqWidth int, stat decor.Statistics)
}

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

reqWidth is requested width set by `func WithWidth(int) ContainerOption`.
If not set, it defaults to terminal width.

func NewBarFiller

func NewBarFiller(b BarFillerBuilder) BarFiller

NewBarFiller constructs a BarFiller from provided BarFillerBuilder. Deprecated. Prefer using `*Progress.New(...)` directly.

type BarFillerBuilder

type BarFillerBuilder interface {
	Build() BarFiller
}

BarFillerBuilder interface. Default implementations are:

BarStyle()
SpinnerStyle()
NopStyle()

func NopStyle added in v7.3.0

func NopStyle() BarFillerBuilder

NopStyle provides BarFillerBuilder which builds NOP BarFiller.

type BarFillerBuilderFunc added in v7.3.0

type BarFillerBuilderFunc func() BarFiller

BarFillerBuilderFunc is function type adapter to convert compatible function into BarFillerBuilder interface.

func (BarFillerBuilderFunc) Build added in v7.3.0

func (f BarFillerBuilderFunc) Build() BarFiller

type BarFillerFunc

type BarFillerFunc func(w io.Writer, reqWidth int, stat decor.Statistics)

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

func (BarFillerFunc) Fill

func (f BarFillerFunc) Fill(w io.Writer, reqWidth int, stat decor.Statistics)

type BarOption

type BarOption func(*bState)

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

func AppendDecorators

func AppendDecorators(decorators ...decor.Decorator) BarOption

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

func BarExtender

func BarExtender(filler BarFiller) 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 be printed after the bar itself.

func BarExtenderRev added in v7.5.0

func BarExtenderRev(filler BarFiller) BarOption

BarExtenderRev extends bar with arbitrary lines in reverse order. Provided BarFiller will be called at each render/flush cycle. Any lines written to the underlying io.Writer will be printed before the bar itself.

func BarFillerClearOnComplete

func BarFillerClearOnComplete() BarOption

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

func BarFillerMiddleware

func BarFillerMiddleware(middle func(BarFiller) BarFiller) BarOption

BarFillerMiddleware provides a way to augment the underlying BarFiller.

func BarFillerOnComplete

func BarFillerOnComplete(message string) BarOption

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

func BarFillerTrim

func BarFillerTrim() BarOption

BarFillerTrim removes leading and trailing space around the underlying BarFiller.

func BarID

func BarID(id int) BarOption

BarID sets bar id.

func BarNoPop

func BarNoPop() BarOption

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

func BarOptOn

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

BarOptOn will invoke provided option only when higher order predicate evaluates to true.

func BarOptional

func BarOptional(option BarOption, cond bool) BarOption

BarOptional will invoke provided option only when cond is true.

func BarPriority

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

func BarQueueAfter(bar *Bar, sync bool) 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. If sync is true queued bar is suspended until argument bar completes or aborts.

func BarRemoveOnComplete

func BarRemoveOnComplete() BarOption

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

func BarWidth

func BarWidth(width int) BarOption

BarWidth sets bar width independent of the container.

func PrependDecorators

func PrependDecorators(decorators ...decor.Decorator) BarOption

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

type BarStyleComposer

type BarStyleComposer interface {
	BarFillerBuilder
	Lbound(string) BarStyleComposer
	Rbound(string) BarStyleComposer
	Filler(string) BarStyleComposer
	Refiller(string) BarStyleComposer
	Padding(string) BarStyleComposer
	TipOnComplete(string) BarStyleComposer
	Tip(frames ...string) BarStyleComposer
	Reverse() BarStyleComposer
}

BarStyleComposer interface.

func BarStyle

func BarStyle() BarStyleComposer

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

type ContainerOption

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 ContainerOptOn

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

ContainerOptOn will invoke provided option only when higher order predicate evaluates to true.

func ContainerOptional

func ContainerOptional(option ContainerOption, cond bool) ContainerOption

ContainerOptional will invoke provided option only when cond is true.

func PopCompletedMode

func PopCompletedMode() ContainerOption

PopCompletedMode will pop and stop rendering completed bars.

func WithDebugOutput

func WithDebugOutput(w io.Writer) ContainerOption

WithDebugOutput sets debug output.

func WithManualRefresh

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

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

func WithOutput

func WithOutput(w io.Writer) ContainerOption

WithOutput overrides default os.Stdout output. Setting it to nil will effectively disable auto refresh rate and discard any output, useful if you want to disable progress bars with little overhead.

func WithRefreshRate

func WithRefreshRate(d time.Duration) ContainerOption

WithRefreshRate overrides default 150ms refresh rate.

func WithRenderDelay

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

func WithShutdownNotifier(ch chan struct{}) ContainerOption

WithShutdownNotifier provided chanel will be closed, after all bars have been rendered.

func WithWaitGroup

func WithWaitGroup(wg *sync.WaitGroup) ContainerOption

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

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`.

type Progress

type Progress struct {
	// contains filtered or unexported fields
}

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

func New

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.

func NewWithContext

func NewWithContext(ctx context.Context, options ...ContainerOption) *Progress

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

func (*Progress) Add

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

Add creates a bar which renders itself by provided filler. If `total <= 0` triggering complete event by increment methods is disabled. Panics if *Progress instance is done, i.e. called after (*Progress).Wait().

func (*Progress) AddBar

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

AddBar creates a bar with default bar filler.

func (*Progress) AddSpinner

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

AddSpinner creates a bar with default spinner filler.

func (*Progress) BarCount

func (p *Progress) BarCount() int

BarCount returns bars count.

func (*Progress) New added in v7.3.0

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

New creates a bar with provided BarFillerBuilder.

func (*Progress) UpdateBarPriority

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

UpdateBarPriority same as *Bar.SetPriority(int).

func (*Progress) Wait

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.

type SpinnerStyleComposer

type SpinnerStyleComposer interface {
	BarFillerBuilder
	PositionLeft() SpinnerStyleComposer
	PositionRight() SpinnerStyleComposer
}

SpinnerStyleComposer interface.

func SpinnerStyle

func SpinnerStyle(frames ...string) SpinnerStyleComposer

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

Directories

Path Synopsis
Package cwriter is a console writer abstraction for the underlying OS.
Package cwriter is a console writer abstraction for the underlying OS.
Package decor provides common decorators for "github.com/vbauerster/mpb/v7" module.
Package decor provides common decorators for "github.com/vbauerster/mpb/v7" module.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL