Zack Scholl

zack.scholl@gmail.com

Progress bar

 / #golang #software #portfolio 

A simple thread-safe Go library progress bar.

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

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

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.

 1req, _ := http.NewRequest("GET", "https://dl.google.com/go/go1.14.2.src.tar.gz", nil)
 2resp, _ := http.DefaultClient.Do(req)
 3defer resp.Body.Close()
 4
 5f, _ := os.OpenFile("go1.14.2.src.tar.gz", os.O_CREATE|os.O_WRONLY, 0644)
 6defer f.Close()
 7
 8bar := progressbar.DefaultBytes(
 9    resp.ContentLength,
10    "downloading",
11)
12io.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.

 1bar := progressbar.NewOptions(1000,
 2    progressbar.OptionSetWriter(ansi.NewAnsiStdout()),
 3    progressbar.OptionEnableColorCodes(true),
 4    progressbar.OptionShowBytes(true),
 5    progressbar.OptionSetWidth(15),
 6    progressbar.OptionSetDescription("[cyan][1/3][reset] Writing moshable file..."),
 7    progressbar.OptionSetTheme(progressbar.Theme{
 8        Saucer:        "[green]=[reset]",
 9        SaucerHead:    "[green]>[reset]",
10        SaucerPadding: " ",
11        BarStart:      "[",
12        BarEnd:        "]",
13    }))
14for i := 0; i < 1000; i++ {
15    bar.Add(1)
16    time.Sleep(5 * time.Millisecond)
17}

which looks like: Example of customized bar

Contributing

Pull requests are welcome. Feel free to…

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.