mpb

package module
v3.2.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2018 License: BSD-3-Clause Imports: 16 Imported by: 0

README

Multi Progress Bar

GoDoc Build Status Go Report Card codecov

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 Addition: Additional bar could be added at later time
  • Dynamic Removal: Remove particular bar, before or after completion
  • Dynamic Resize: Adaptive bar resize (doesn't work inside tmux)
  • Cancellation: Cancel whole rendering process
  • Predefined Decorators: Elapsed time, Ewmaest based ETA, Percentage, Bytes counter
  • Decorator's width sync: Synchronized decorator's width among multiple bars

Installation

go get github.com/vbauerster/mpb

Note: it is preferable to go get from github.com, rather than gopkg.in. See issue #11.

Usage

Rendering single bar
	p := mpb.New(
		// override default (80) width
		mpb.WithWidth(100),
		// override default "[=>-]" format
		mpb.WithFormat("╢▌▌░╟"),
		// override default 120ms refresh rate
		mpb.WithRefreshRate(100*time.Millisecond),
	)

	total := 100
	name := "Single Bar:"
	// Add a bar
	// You're not limited to just a single bar, add as many as you need
	bar := p.AddBar(int64(total),
		// Prepending decorators
		mpb.PrependDecorators(
			// StaticName decorator with minWidth and no extra config
			// If you need to change name while rendering, use DynamicName
			decor.StaticName(name, len(name), 0),
			// ETA decorator with minWidth and no extra config
			decor.ETA(4, 0),
		),
		// Appending decorators
		mpb.AppendDecorators(
			// Percentage decorator with minWidth and no extra config
			decor.Percentage(5, 0),
		),
	)

	max := 200 * time.Millisecond
	for i := 0; i < total; i++ {
		time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10)
		bar.Increment()
	}
	// Wait for all bars to complete
	p.Wait()
Rendering multiple bars
	var wg sync.WaitGroup
	p := mpb.New(mpb.WithWaitGroup(&wg))
	total := 100
	numBars := 3
	wg.Add(numBars)

	for i := 0; i < numBars; i++ {
		name := fmt.Sprintf("Bar#%d:", i)
		bar := p.AddBar(int64(total),
			mpb.PrependDecorators(
				decor.StaticName(name, 0, 0),
				// DSyncSpace is shortcut for DwidthSync|DextraSpace
				// means sync the width of respective decorator's column
				// and prepend one extra space.
				decor.Percentage(3, decor.DSyncSpace),
			),
			mpb.AppendDecorators(
				decor.ETA(3, 0),
			),
		)
		go func() {
			defer wg.Done()
			max := 200 * time.Millisecond
			for i := 0; i < total; i++ {
		        time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10)
				bar.Increment()
			}
		}()
	}
	// Wait for all bars to complete
	p.Wait()
Dynamic Total

dynTotal.gif

Adaptive resize

resize.gif

Note: don't expect much, it corrupts if resizing too fast.

Bytes counter decorator

io-multiple.gif

Typeface used in screen shots: Iosevka

Documentation

Overview

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

Example
package main

import (
	"math/rand"
	"time"

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

func main() {
	p := mpb.New(
		// override default (80) width
		mpb.WithWidth(100),
		// override default "[=>-]" format
		mpb.WithFormat("╢▌▌░╟"),
		// override default 120ms refresh rate
		mpb.WithRefreshRate(100*time.Millisecond),
	)

	total := 100
	name := "Single Bar:"
	// Add a bar
	// You're not limited to just a single bar, add as many as you need
	bar := p.AddBar(int64(total),
		// Prepending decorators
		mpb.PrependDecorators(
			// StaticName decorator with minWidth and no extra config
			// If you need to change name while rendering, use DynamicName
			decor.StaticName(name, len(name), 0),
			// ETA decorator with minWidth and no extra config
			decor.ETA(4, 0),
		),
		// Appending decorators
		mpb.AppendDecorators(
			// Percentage decorator with minWidth and no extra config
			decor.Percentage(5, 0),
		),
	)

	max := 200 * time.Millisecond
	for i := 0; i < total; i++ {
		time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10)
		bar.Increment()
	}
	// Wait for all bars to complete
	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) Complete

func (b *Bar) Complete()

Complete stops bar's progress tracking, but doesn't remove the bar from rendering queue. If you need to remove, invoke Progress.RemoveBar(*Bar) instead.

func (*Bar) Completed

func (b *Bar) Completed() bool

Completed reports whether the bar is in completed state

Example
package main

import (
	"math/rand"
	"time"

	"github.com/vbauerster/mpb"
)

func main() {
	p := mpb.New()
	bar := p.AddBar(100)

	max := 200 * 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 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)

IncrBy increments progress bar by amount of n

func (*Bar) Increment

func (b *Bar) Increment()

Increment is a shorthand for b.IncrBy(1)

func (*Bar) NumOfAppenders

func (b *Bar) NumOfAppenders() int

NumOfAppenders returns current number of append decorators

func (*Bar) NumOfPrependers

func (b *Bar) NumOfPrependers() int

NumOfPrependers returns current number of prepend decorators

func (*Bar) ProxyReader

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

ProxyReader wrapper for io operations, like io.Copy

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

func (b *Bar) ResumeFill(r rune, till int64)

ResumeFill fills bar with different r rune, from 0 to till amount of progress.

func (*Bar) SetTotal

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

SetTotal sets total dynamically. The final param indicates the very last set, in other words you should set it to true when total is determined.

func (*Bar) Total

func (b *Bar) Total() int64

Total returns bar's total number.

type BarOption

type BarOption func(*bState)

BarOption is a function option which changes the default behavior of a bar, if passed to p.AddBar(int64, ...BarOption)

func AppendDecorators

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

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

func BarAutoIncrTotal

func BarAutoIncrTotal(trigger, amount int64) BarOption

BarAutoIncrTotal auto increment total by amount, when trigger percentage remained till bar completion. In other words: say you've set trigger = 10, then auto increment will start after bar reaches 90 %.

func BarDynamicTotal

func BarDynamicTotal() BarOption

BarDynamicTotal enables dynamic total behaviour.

func BarEtaAlpha

func BarEtaAlpha(a float64) BarOption

BarEtaAlpha option is a way to adjust ETA behavior. You can play with it, if you're not satisfied with default behavior. Default value is 0.25.

func BarID

func BarID(id int) BarOption

BarID overwrites internal bar id

func BarTrim

func BarTrim() BarOption

BarTrim trims both left and right spaces of the bar

func BarTrimLeft

func BarTrimLeft() BarOption

BarTrimLeft trims left side space of the bar

func BarTrimRight

func BarTrimRight() BarOption

BarTrimRight trims right space of the bar

func PrependDecorators

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

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

type Progress

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

Progress represents the container that renders Progress bars

func New

func New(options ...ProgressOption) *Progress

New creates new Progress instance, which orchestrates bars rendering process. Accepts mpb.ProgressOption funcs for customization.

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

func (p *Progress) BarCount() int

BarCount returns bars count

func (*Progress) RemoveBar

func (p *Progress) RemoveBar(b *Bar) bool

RemoveBar removes the bar at next render cycle

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 first waits for all bars to complete, then waits for user provided WaitGroup, if any. It's optional to call, in other words if you don't call Progress.Wait(), it's not guaranteed that all bars will be flushed completely to the underlying io.Writer.

type ProgressOption

type ProgressOption func(*pState)

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

func Output

func Output(w io.Writer) ProgressOption

Output overrides default output os.Stdout

func OutputInterceptors

func OutputInterceptors(interseptors ...func(io.Writer)) ProgressOption

OutputInterceptors provides a way to write to the underlying progress pool's writer. Could be useful if you want to output something below the bars, while they're rendering.

func WithCancel

func WithCancel(ch <-chan struct{}) ProgressOption

WithCancel provide your cancel channel, which you plan to close at some point.

func WithContext

func WithContext(ctx context.Context) ProgressOption

WithContext provided context will be used for cancellation purposes

func WithFormat

func WithFormat(format string) ProgressOption

WithFormat overrides default bar format "[=>-]"

func WithRefreshRate

func WithRefreshRate(d time.Duration) ProgressOption

WithRefreshRate overrides default 120ms refresh rate

func WithShutdownNotifier

func WithShutdownNotifier(ch chan struct{}) ProgressOption

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

func WithWaitGroup

func WithWaitGroup(wg *sync.WaitGroup) ProgressOption

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

WithWidth overrides default width 80

type Reader

type Reader struct {
	io.Reader
	// contains filtered or unexported fields
}

Reader is io.Reader wrapper, for proxy read bytes

func (*Reader) Close

func (r *Reader) Close() error

Close the reader when it implements io.Closer

func (*Reader) Read

func (r *Reader) Read(p []byte) (int, error)

Jump to

Keyboard shortcuts

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