mpb

package module
v4.5.1 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2019 License: BSD-3-Clause Imports: 15 Imported by: 59

README

Multi Progress Bar

GoDoc Build Status Go Report Card

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/v4"
    "github.com/vbauerster/mpb/v4/decor"
)

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

    total := 100
    name := "Single Bar:"
    // adding a single bar, which will inherit container's width
    bar := p.AddBar(int64(total),
        // set custom bar style, default one is "[=>-]"
        mpb.BarStyle("╢▌▌░╟"),
        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 := time.Now()
        time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10)
        // ewma based decorators require work duration measurement
        bar.IncrBy(1, time.Since(start))
    }
    // wait for our bar to complete and flush
    p.Wait()
}
Rendering multiple bars
    var wg sync.WaitGroup
    // pass &wg (optional), so p will wait for it eventually
    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), "done",
                ),
            ),
        )
        // simulating some work
        go func() {
            defer wg.Done()
            max := 100 * time.Millisecond
            for i := 0; i < total; i++ {
                start := time.Now()
                time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10)
                // ewma based decorators require work duration measurement
                bar.IncrBy(1, time.Since(start))
            }
        }()
    }
    // Waiting 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:"
// adding a single bar, which will inherit container's width
bar := p.AddBar(int64(total),
	// set custom bar style, default one is "[=>-]"
	mpb.BarStyle("╢▌▌░╟"),
	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 := time.Now()
	time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10)
	// ewma based decorators require work duration measurement
	bar.IncrBy(1, time.Since(start))
}
// wait for our bar to complete and flush
p.Wait()

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) 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()

func (*Bar) Current

func (b *Bar) Current() int64

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

func (*Bar) ID

func (b *Bar) ID() int

ID returs id of the bar.

func (*Bar) IncrBy

func (b *Bar) IncrBy(n int, wdd ...time.Duration)

IncrBy increments progress bar by amount of n. wdd is optional work duration i.e. time.Since(start), which expected to be provided, if any ewma based decorator is used.

func (*Bar) Increment

func (b *Bar) Increment()

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

func (*Bar) ProxyReader

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

ProxyReader wraps r with metrics required for progress tracking.

Example
p := mpb.New()
// make http get request, ignoring errors
resp, _ := http.Get("https://homebrew.bintray.com/bottles/libtiff-4.0.7.sierra.bottle.tar.gz")
defer resp.Body.Close()

// Assuming ContentLength > 0
bar := p.AddBar(resp.ContentLength,
	mpb.AppendDecorators(
		decor.CountersKibiByte("%6.1f / %6.1f"),
	),
)

// create proxy reader
reader := bar.ProxyReader(resp.Body)

// and copy from reader, ignoring errors
io.Copy(ioutil.Discard, reader)

p.Wait()

func (*Bar) RemoveAllAppenders

func (b *Bar) RemoveAllAppenders()

RemoveAllAppenders removes all append functions.

func (*Bar) RemoveAllPrependers

func (b *Bar) RemoveAllPrependers()

RemoveAllPrependers removes all prepend functions.

func (*Bar) SetCurrent added in v4.4.0

func (b *Bar) SetCurrent(current int64, wdd ...time.Duration)

SetCurrent sets progress' current to arbitrary amount.

func (*Bar) SetRefill

func (b *Bar) SetRefill(amount int64)

SetRefill sets refill, if supported by underlying Filler.

func (*Bar) SetTotal

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

SetTotal sets total dynamically. Set toComplete to true, to trigger bar complete event now.

type BarOption

type BarOption func(*bState)

BarOption is a function option which changes the default behavior of a bar.

func AppendDecorators

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

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

func BarClearOnComplete

func BarClearOnComplete() BarOption

BarClearOnComplete is a flag, if set will clear bar section on complete event. If you need to remove a whole bar line, refer to BarRemoveOnComplete.

func BarExtender

func BarExtender(extender Filler) BarOption

BarExtender is an option to extend bar to the next new line, with arbitrary output.

func BarID

func BarID(id int) BarOption

BarID sets bar id.

func BarOptOnCond added in v4.1.0

func BarOptOnCond(option BarOption, condition func() bool) BarOption

BarOptOnCond returns option when condition evaluates to true.

func BarParkTo added in v4.5.0

func BarParkTo(runningBar *Bar) BarOption

BarParkTo parks constructed bar into the runningBar. In other words, constructed bar will start only after runningBar has been completed. Parked bar will replace runningBar if BarRemoveOnComplete option is set on the runningBar. Parked bar inherits priority of the runningBar, if no BarPriority option is set.

func BarPriority

func BarPriority(priority int) BarOption

BarPriority sets bar's priority. Zero is highest priority, i.e. bar will be on top. If `BarReplaceOnComplete` option is supplied, this option is ignored.

func BarRemoveOnComplete

func BarRemoveOnComplete() BarOption

BarRemoveOnComplete is a flag, if set whole bar line will be removed on complete event. If both BarRemoveOnComplete and BarClearOnComplete are set, first bar section gets cleared and then whole bar line gets removed completely.

func BarReplaceOnComplete

func BarReplaceOnComplete(runningBar *Bar) BarOption

BarReplaceOnComplete is deprecated. Refer to BarParkTo option.

func BarReverse added in v4.3.0

func BarReverse() BarOption

BarReverse reverse mode, bar will progress from right to left.

func BarStyle

func BarStyle(style string) BarOption

BarStyle sets custom bar style, default one is "[=>-]<+".

'[' left bracket rune

'=' fill rune

'>' tip rune

'-' empty rune

']' right bracket rune

'<' reverse tip rune, used when BarReverse option is set

'+' refill rune, used when *Bar.SetRefill(int64) is called

It's ok to provide first five runes only, for example mpb.BarStyle("╢▌▌░╟")

func BarWidth

func BarWidth(width int) BarOption

BarWidth sets bar width independent of the container.

func MakeFillerTypeSpecificBarOption

func MakeFillerTypeSpecificBarOption(
	typeChecker func(Filler) (interface{}, bool),
	cb func(interface{}),
) BarOption

MakeFillerTypeSpecificBarOption makes BarOption specific to Filler's actual type. If you implement your own Filler, so most probably you'll need this. See BarStyle or SpinnerStyle for example.

func PrependDecorators

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

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

func SpinnerStyle

func SpinnerStyle(frames []string) BarOption

SpinnerStyle sets custom spinner style. Effective when Filler type is spinner.

func TrimSpace

func TrimSpace() BarOption

TrimSpace trims bar's edge spaces.

type ContainerOption added in v4.1.0

type ContainerOption func(*pState)

ContainerOption is a function option which changes the default behavior of progress container, if passed to mpb.New(...ContainerOption).

func ContainerOptOnCond added in v4.1.0

func ContainerOptOnCond(option ContainerOption, condition func() bool) ContainerOption

ContainerOptOnCond returns option when condition evaluates to true.

func WithContext

func WithContext(ctx context.Context) ContainerOption

WithContext deprecated and has no effect, please use NewWithContext instead.

func WithDebugOutput

func WithDebugOutput(w io.Writer) ContainerOption

WithDebugOutput sets debug output.

func WithManualRefresh

func WithManualRefresh(ch <-chan time.Time) 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, usefull if you want to disable progress bars with little overhead.

func WithRefreshRate

func WithRefreshRate(d time.Duration) ContainerOption

WithRefreshRate overrides default 120ms refresh rate.

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(w int) ContainerOption

WithWidth sets container width. Default is 80. Bars inherit this width, as long as no BarWidth is applied.

type Filler

type Filler interface {
	Fill(w io.Writer, width int, stat *decor.Statistics)
}

Filler interface. Bar renders by calling Filler's Fill method. You can literally have any bar kind, by implementing this interface and passing it to the Add method.

type FillerFunc

type FillerFunc func(w io.Writer, width int, stat *decor.Statistics)

FillerFunc is function type adapter to convert function into Filler.

func (FillerFunc) Fill

func (f FillerFunc) Fill(w io.Writer, width int, stat *decor.Statistics)

type Progress

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

Progress represents the container that renders 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 added in v4.5.0

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) Abort

func (p *Progress) Abort(b *Bar, remove bool)

Abort is only effective while bar progress is running, it means remove bar now without waiting for its completion. If bar is already completed, there is nothing to abort. If you need to remove bar after completion, use BarRemoveOnComplete BarOption.

func (*Progress) Add

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

Add creates a bar which renders itself by provided filler. Set total to 0, if you plan to update it later.

func (*Progress) AddBar

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

AddBar creates a new progress bar and adds to the container.

func (*Progress) AddSpinner

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

AddSpinner creates a new spinner bar and adds to the container.

func (*Progress) BarCount

func (p *Progress) BarCount() int

BarCount returns bars count

func (*Progress) UpdateBarPriority

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

UpdateBarPriority provides a way to change bar's order position. Zero is highest priority, i.e. bar will be on top.

func (*Progress) Wait

func (p *Progress) Wait()

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

type SpinnerAlignment

type SpinnerAlignment int

SpinnerAlignment enum.

const (
	SpinnerOnLeft SpinnerAlignment = iota
	SpinnerOnMiddle
	SpinnerOnRight
)

SpinnerAlignment kinds.

Directories

Path Synopsis
_examples
barExtender command
cancel command
complex command
differentWidth command
dynTotal command
io command
multiBars command
panic command
quietMode command
remove command
reverseBar command
singleBar command
sortBars command
spinnerBar command
stress command
Package decor contains common decorators used by "github.com/vbauerster/mpb" package.
Package decor contains common decorators used by "github.com/vbauerster/mpb" package.

Jump to

Keyboard shortcuts

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