progressbar

package module
v3.17.1 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2024 License: MIT Imports: 13 Imported by: 1,644

README

progressbar

CI go report card coverage godocs

A very simple thread-safe progress bar which should work on every OS without problems. I needed a progressbar for croc and everything I tried had problems, so I made another one. In order to be OS agnostic I do not plan to support multi-line outputs.

Install

go get -u github.com/schollz/progressbar/v3

Usage

Basic usage
bar := progressbar.Default(100)
for i := 0; i < 100; i++ {
    bar.Add(1)
    time.Sleep(40 * time.Millisecond)
}

which looks like:

Example of basic bar

I/O operations

The progressbar implements an io.Writer so it can automatically detect the number of bytes written to a stream, so you can use it as a progressbar for an io.Reader.

req, _ := http.NewRequest("GET", "https://dl.google.com/go/go1.14.2.src.tar.gz", nil)
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

f, _ := os.OpenFile("go1.14.2.src.tar.gz", os.O_CREATE|os.O_WRONLY, 0644)
defer f.Close()

bar := progressbar.DefaultBytes(
    resp.ContentLength,
    "downloading",
)
io.Copy(io.MultiWriter(f, bar), resp.Body)

which looks like:

Example of download bar

Progress bar with unknown length

A progressbar with unknown length is a spinner. Any bar with -1 length will automatically convert it to a spinner with a customizable spinner type. For example, the above code can be run and set the resp.ContentLength to -1.

which looks like:

Example of download bar with unknown length

Customization

There is a lot of customization that you can do - change the writer, the color, the width, description, theme, etc. See all the options.

bar := progressbar.NewOptions(1000,
    progressbar.OptionSetWriter(ansi.NewAnsiStdout()), //you should install "github.com/k0kubun/go-ansi"
    progressbar.OptionEnableColorCodes(true),
    progressbar.OptionShowBytes(true),
    progressbar.OptionSetWidth(15),
    progressbar.OptionSetDescription("[cyan][1/3][reset] Writing moshable file..."),
    progressbar.OptionSetTheme(progressbar.Theme{
        Saucer:        "[green]=[reset]",
        SaucerHead:    "[green]>[reset]",
        SaucerPadding: " ",
        BarStart:      "[",
        BarEnd:        "]",
    }))
for i := 0; i < 1000; i++ {
    bar.Add(1)
    time.Sleep(5 * time.Millisecond)
}

which looks like:

Example of customized bar

Contributing

Pull requests are welcome. Feel free to...

  • Revise documentation
  • Add new features
  • Fix bugs
  • Suggest improvements

Thanks

Thanks @Dynom for massive improvements in version 2.0!

Thanks @CrushedPixel for adding descriptions and color code support!

Thanks @MrMe42 for adding some minor features!

Thanks @tehstun for some great PRs!

Thanks @Benzammour and @haseth for helping create v3!

Thanks @briandowns for compiling the list of spinners.

License

MIT

Documentation

Overview

Example (XOutOfY)
bar := NewOptions(100, OptionSetPredictTime(true))

for i := 0; i < 100; i++ {
	bar.Add(1)
	time.Sleep(1 * time.Millisecond)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ThemeDefault is given by default (if not changed with OptionSetTheme), and it looks like "|████     |".
	ThemeDefault = Theme{Saucer: "█", SaucerPadding: " ", BarStart: "|", BarEnd: "|"}

	// ThemeASCII is a predefined Theme that uses ASCII symbols. It looks like "[===>...]".
	// Configure it with OptionSetTheme(ThemeASCII).
	ThemeASCII = Theme{
		Saucer:        "=",
		SaucerHead:    ">",
		SaucerPadding: ".",
		BarStart:      "[",
		BarEnd:        "]",
	}

	// ThemeUnicode is a predefined Theme that uses Unicode characters, displaying a graphic bar.
	// It looks like "" (rendering will depend on font being used).
	// It requires special symbols usually found in "nerd fonts" [2], or in Fira Code [1], and other sources.
	// Configure it with OptionSetTheme(ThemeUnicode).
	//
	// [1] https://github.com/tonsky/FiraCode
	// [2] https://www.nerdfonts.com/
	ThemeUnicode = Theme{
		Saucer:         "\uEE04",
		SaucerHead:     "\uEE04",
		SaucerPadding:  "\uEE01",
		BarStart:       "\uEE00",
		BarStartFilled: "\uEE03",
		BarEnd:         "\uEE02",
		BarEndFilled:   "\uEE05",
	}
)

Functions

func Bprintf added in v3.14.6

func Bprintf(pb *ProgressBar, format string, a ...interface{}) (int, error)

func Bprintln added in v3.14.6

func Bprintln(pb *ProgressBar, a ...interface{}) (int, error)

Types

type Option

type Option func(p *ProgressBar)

Option is the type all options need to adhere to

func OptionClearOnFinish

func OptionClearOnFinish() Option

OptionClearOnFinish will clear the bar once its finished.

Example
bar := NewOptions(100, OptionSetWidth(10), OptionClearOnFinish())
bar.Reset()
bar.Finish()
fmt.Println("Finished")
Output:

Finished

func OptionEnableColorCodes

func OptionEnableColorCodes(colorCodes bool) Option

OptionEnableColorCodes enables or disables support for color codes using mitchellh/colorstring

func OptionFullWidth added in v3.3.0

func OptionFullWidth() Option

OptionFullWidth sets the bar to be full width

func OptionOnCompletion

func OptionOnCompletion(cmpl func()) Option

OptionOnCompletion will invoke cmpl function once its finished

func OptionSetDescription

func OptionSetDescription(description string) Option

OptionSetDescription sets the description of the bar to render in front of it

func OptionSetElapsedTime added in v3.9.0

func OptionSetElapsedTime(elapsedTime bool) Option

OptionSetElapsedTime will enable elapsed time. Always enabled if OptionSetPredictTime is true.

func OptionSetItsString added in v3.4.0

func OptionSetItsString(iterationString string) Option

OptionSetItsString sets what's displayed for iterations a second. The default is "it" which would display: "it/s"

func OptionSetMaxDetailRow added in v3.15.0

func OptionSetMaxDetailRow(row int) Option

OptionSetMaxDetailRow sets the max row of details the row count should be less than the terminal height, otherwise it will not give you the output you want

func OptionSetPredictTime

func OptionSetPredictTime(predictTime bool) Option

OptionSetPredictTime will also attempt to predict the time remaining.

Example
bar := NewOptions(100, OptionSetWidth(10), OptionSetPredictTime(false))
_ = bar.Add(10)
Output:

10% |█         |

func OptionSetRenderBlankState

func OptionSetRenderBlankState(r bool) Option

OptionSetRenderBlankState sets whether or not to render a 0% bar on construction

Example
NewOptions(10, OptionSetWidth(10), OptionSetRenderBlankState(true))
Output:

0% |          |  [0s:0s]

func OptionSetSpinnerChangeInterval added in v3.16.0

func OptionSetSpinnerChangeInterval(interval time.Duration) Option

OptionSetSpinnerChangeInterval sets the spinner change interval the spinner will change according to this value. By default, this value is 100 * time.Millisecond If you don't want to let this progressbar update by specified time interval you can set this value to zero, then the spinner will change each time rendered, such as when Add() or Describe() was called

func OptionSetTheme

func OptionSetTheme(t Theme) Option

OptionSetTheme sets the elements the bar is constructed with. There are two pre-defined themes you can use: ThemeASCII and ThemeUnicode.

func OptionSetVisibility added in v3.5.0

func OptionSetVisibility(visibility bool) Option

OptionSetVisibility sets the visibility

func OptionSetWidth

func OptionSetWidth(s int) Option

OptionSetWidth sets the width of the bar

func OptionSetWriter

func OptionSetWriter(w io.Writer) Option

OptionSetWriter sets the output writer (defaults to os.StdOut)

func OptionShowBytes

func OptionShowBytes(val bool) Option

OptionShowBytes will update the progress bar configuration settings to display/hide kBytes/Sec

Example (Spinner)
/*
	Spinner test with iterations and count
*/
buf := strings.Builder{}
bar := NewOptions(-1,
	OptionSetWidth(10),
	OptionShowBytes(true),
	OptionSetWriter(&buf),
)

bar.Reset()
time.Sleep(1 * time.Second)
// since 10 is the width and we don't know the max bytes
// it will do a infinite scrolling.
bar.Add(11)
bar.lock.Lock()
result, _ := virtualterm.Process(buf.String())
bar.lock.Unlock()
fmt.Print(result)
Output:

-  (11 B/s) [1s]

func OptionShowCount

func OptionShowCount() Option

OptionShowCount will also print current count out of total

Example (Minuscule)
bar := NewOptions(10000, OptionSetWidth(10), OptionShowCount(), OptionSetPredictTime(false))
bar.Add(1)
Output:

0% |          | (1/10000)

func OptionShowDescriptionAtLineEnd added in v3.11.0

func OptionShowDescriptionAtLineEnd() Option

OptionShowDescriptionAtLineEnd defines whether description should be written at line end instead of line start

Example
bar := NewOptions(100, OptionSetWidth(10), OptionShowDescriptionAtLineEnd(), OptionSetDescription("hello"))
_ = bar.Add(10)
Output:

10% |█         |  [0s:0s] hello
Example (Spinner)
bar := NewOptions(-1, OptionSetWidth(10), OptionShowDescriptionAtLineEnd(), OptionSetDescription("hello"))
_ = bar.Add(1)
Output:

|  [0s] hello

func OptionShowElapsedTimeOnFinish added in v3.10.0

func OptionShowElapsedTimeOnFinish() Option

OptionShowElapsedTimeOnFinish will keep the display of elapsed time on finish.

func OptionShowIts

func OptionShowIts() Option

OptionShowIts will also print the iterations/second

Example
bar := NewOptions(100, OptionSetWidth(10), OptionShowIts(), OptionSetPredictTime(false))
bar.Reset()
time.Sleep(1 * time.Second)
bar.Add(10)
Output:

10% |█         | (10 it/s)
Example (Count)
bar := NewOptions(100, OptionSetWidth(10), OptionShowIts(), OptionShowCount())
bar.Reset()
time.Sleep(1 * time.Second)
bar.Add(10)
Output:

10% |█         | (10/100, 10 it/s) [1s:9s]
Example (Spinner)
/*
	Spinner test with iteration count and iteration rate
*/
vt := virtualterm.NewDefault()
bar := NewOptions(-1,
	OptionSetWidth(10),
	OptionShowIts(),
	OptionShowCount(),
	OptionSetWriter(&vt),
)
bar.Reset()
time.Sleep(1 * time.Second)
bar.Add(5)
bar.lock.Lock()
s, err := vt.String()
bar.lock.Unlock()
if err != nil {
	log.Fatal(err)
}
fmt.Print(s)
Output:

-  (5/-, 5 it/s) [1s]

func OptionShowTotalBytes added in v3.17.0

func OptionShowTotalBytes(flag bool) Option

OptionShowTotalBytes will keep the display of total bytes.

func OptionSpinnerCustom added in v3.13.0

func OptionSpinnerCustom(spinner []string) Option

OptionSpinnerCustom sets the spinner used for indeterminate bars to the passed slice of string

func OptionSpinnerType added in v3.2.0

func OptionSpinnerType(spinnerType int) Option

OptionSpinnerType sets the type of spinner used for indeterminate bars

func OptionThrottle

func OptionThrottle(duration time.Duration) Option

OptionThrottle will wait the specified duration before updating again. The default duration is 0 seconds.

Example
bar := NewOptions(100, OptionSetWidth(10), OptionThrottle(100*time.Millisecond))
bar.Reset()
bar.Add(5)
time.Sleep(150 * time.Millisecond)
bar.Add(5)
bar.Add(10)
Output:

10% |█         |  [0s:1s]

func OptionUseANSICodes added in v3.7.0

func OptionUseANSICodes(val bool) Option

OptionUseANSICodes will use more optimized terminal i/o.

Only useful in environments with support for ANSI escape sequences.

func OptionUseIECUnits added in v3.14.0

func OptionUseIECUnits(val bool) Option

OptionUseIECUnits will enable IEC units (e.g. MiB) instead of the default SI units (e.g. MB).

type ProgressBar

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

ProgressBar is a thread-safe, simple progress bar

Example
bar := New(100)
bar.Add(10)
Output:

10% |████                                    |  [0s:0s]
Example (Basic)
bar := NewOptions(100, OptionSetWidth(10))
bar.Reset()
time.Sleep(1 * time.Second)
bar.Add(10)
Output:

10% |█         |  [1s:9s]
Example (Invisible)
bar := NewOptions(100, OptionSetWidth(10), OptionSetRenderBlankState(true), OptionSetVisibility(false))
bar.Reset()
fmt.Println("hello, world")
time.Sleep(1 * time.Second)
bar.Add(10)
Output:

hello, world

func Default added in v3.3.0

func Default(max int64, description ...string) *ProgressBar

Default provides a progressbar with recommended defaults. Set max to -1 to use as a spinner.

Example
bar := Default(100)
for i := 0; i < 50; i++ {
	bar.Add(1)
	time.Sleep(10 * time.Millisecond)
}
Output:

func DefaultBytes added in v3.3.0

func DefaultBytes(maxBytes int64, description ...string) *ProgressBar

DefaultBytes provides a progressbar to measure byte throughput with recommended defaults. Set maxBytes to -1 to use as a spinner.

func DefaultBytesSilent added in v3.8.0

func DefaultBytesSilent(maxBytes int64, description ...string) *ProgressBar

DefaultBytesSilent is the same as DefaultBytes, but does not output anywhere. String() can be used to get the output instead.

func DefaultSilent added in v3.8.0

func DefaultSilent(max int64, description ...string) *ProgressBar

DefaultSilent is the same as Default, but does not output anywhere. String() can be used to get the output instead.

func New

func New(max int) *ProgressBar

New returns a new ProgressBar with the specified maximum

func New64

func New64(max int64) *ProgressBar

New64 returns a new ProgressBar with the specified maximum

func NewOptions

func NewOptions(max int, options ...Option) *ProgressBar

NewOptions constructs a new instance of ProgressBar, with any options you specify

func NewOptions64

func NewOptions64(max int64, options ...Option) *ProgressBar

NewOptions64 constructs a new instance of ProgressBar, with any options you specify

func (*ProgressBar) Add

func (p *ProgressBar) Add(num int) error

Add will add the specified amount to the progressbar

func (*ProgressBar) Add64

func (p *ProgressBar) Add64(num int64) error

Add64 will add the specified amount to the progressbar

func (*ProgressBar) AddDetail added in v3.15.0

func (p *ProgressBar) AddDetail(detail string) error

AddDetail adds a detail to the progress bar. Only used when maxDetailRow is set to a value greater than 0

func (*ProgressBar) ChangeMax added in v3.1.0

func (p *ProgressBar) ChangeMax(newMax int)

ChangeMax takes in a int and changes the max value of the progress bar

Example
bar := NewOptions(100, OptionSetWidth(10), OptionSetPredictTime(false))
bar.ChangeMax(50)
bar.Add(50)
Output:

100% |██████████|

func (*ProgressBar) ChangeMax64 added in v3.1.0

func (p *ProgressBar) ChangeMax64(newMax int64)

ChangeMax64 is basically the same as ChangeMax, but takes in a int64 to avoid casting

func (*ProgressBar) Clear

func (p *ProgressBar) Clear() error

Clear erases the progress bar from the current line

func (*ProgressBar) Close added in v3.8.0

func (p *ProgressBar) Close() (err error)

func (*ProgressBar) Describe

func (p *ProgressBar) Describe(description string)

Describe will change the description shown before the progress, which can be changed on the fly (as for a slow running process).

func (*ProgressBar) Exit added in v3.12.0

func (p *ProgressBar) Exit() error

Exit will exit the bar to keep current state

func (*ProgressBar) Finish

func (p *ProgressBar) Finish() error

Finish will fill the bar to full

Example
bar := NewOptions(100, OptionSetWidth(10), OptionShowCount(), OptionShowBytes(true), OptionShowIts())
bar.Reset()
time.Sleep(1 * time.Second)
bar.Finish()
Output:

100% |██████████| (100/100 B, 100 B/s, 100 it/s)

func (*ProgressBar) GetMax

func (p *ProgressBar) GetMax() int

GetMax returns the max of a bar

func (*ProgressBar) GetMax64

func (p *ProgressBar) GetMax64() int64

GetMax64 returns the current max

func (*ProgressBar) IsFinished added in v3.6.0

func (p *ProgressBar) IsFinished() bool

IsFinished returns true if progress bar is completed

func (*ProgressBar) IsStarted added in v3.15.0

func (p *ProgressBar) IsStarted() bool

IsStarted returns true if progress bar is started

func (*ProgressBar) Read

func (p *ProgressBar) Read(b []byte) (n int, err error)

Read implement io.Reader

func (*ProgressBar) RenderBlank

func (p *ProgressBar) RenderBlank() error

RenderBlank renders the current bar state, you can use this to render a 0% state

func (*ProgressBar) Reset

func (p *ProgressBar) Reset()

Reset will reset the clock that is used to calculate current time and the time left.

func (*ProgressBar) Set

func (p *ProgressBar) Set(num int) error

Set will set the bar to a current number

Example
bar := New(100)
bar.Set(10)
Output:

10% |████                                    |  [0s:0s]

func (*ProgressBar) Set64

func (p *ProgressBar) Set64(num int64) error

Set64 will set the bar to a current number

Example
bar := New(100)
bar.Set64(10)
Output:

10% |████                                    |  [0s:0s]

func (*ProgressBar) StartWithoutRender added in v3.15.0

func (p *ProgressBar) StartWithoutRender()

StartWithoutRender will start the progress bar without rendering it this method is created for the use case where you want to start the progress but don't want to render it immediately. If you want to start the progress and render it immediately, use RenderBlank instead, or maybe you can use Add to start it automatically, but it will make the time calculation less precise.

func (*ProgressBar) State

func (p *ProgressBar) State() State

State returns the current state

func (*ProgressBar) String added in v3.8.0

func (p *ProgressBar) String() string

String returns the current rendered version of the progress bar. It will never return an empty string while the progress bar is running.

func (*ProgressBar) Write

func (p *ProgressBar) Write(b []byte) (n int, err error)

Write implement io.Writer

type Reader

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

Reader is the progressbar io.Reader struct

func NewReader added in v3.6.2

func NewReader(r io.Reader, bar *ProgressBar) Reader

NewReader return a new Reader with a given progress bar.

func (*Reader) Close

func (r *Reader) Close() (err error)

Close the reader when it implements io.Closer

func (*Reader) Read

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

Read will read the data and add the number of bytes to the progressbar

type State

type State struct {
	Max            int64
	CurrentNum     int64
	CurrentPercent float64
	CurrentBytes   float64
	SecondsSince   float64
	SecondsLeft    float64
	KBsPerSecond   float64
	Description    string
}

State is the basic properties of the bar

type Theme

type Theme struct {
	Saucer        string
	AltSaucerHead string
	SaucerHead    string
	SaucerPadding string
	BarStart      string
	BarEnd        string

	// BarStartFilled is used after the Bar starts filling, if set. Otherwise, it defaults to BarStart.
	BarStartFilled string

	// BarEndFilled is used once the Bar finishes, if set. Otherwise, it defaults to BarEnd.
	BarEndFilled string
}

Theme defines the elements of the bar

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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