progress

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: May 1, 2026 License: MIT Imports: 12 Imported by: 5 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package progress provide terminal progress bar display. Such as: `Txt`, `Bar`, `Loading`, `RoundTrip`, `DynamicText` ...

Index

Examples

Constants

View Source
const (
	CharStar    rune = '*'
	CharPlus    rune = '+'
	CharWell    rune = '#'
	CharEqual   rune = '='
	CharEqual1  rune = '═'
	CharSpace   rune = ' '
	CharCenter  rune = '●'
	CharSquare  rune = '■'
	CharSquare1 rune = '▇'
	CharSquare2 rune = '▉'
	CharSquare3 rune = '░'
	CharSquare4 rune = '▒'
	CharSquare5 rune = '▢'
	// CharHyphen Minus
	CharHyphen      rune = '-'
	CharCNHyphen    rune = '—'
	CharUnderline   rune = '_'
	CharLeftArrow   rune = '<'
	CharRightArrow  rune = '>'
	CharRightArrow1 rune = '▶'
)

some built in chars

View Source
const (
	MinFormat  = "{@message}{@current}"
	TxtFormat  = "{@message}{@percent:4s}%({@current}/{@max})"
	DefFormat  = "{@message}{@percent:4s}%({@current}/{@max})"
	FullFormat = "{@percent:4s}%({@current}/{@max}) {@elapsed:7s}/{@estimated:-7s} {@memory:6s}"
)

internal format for text progress

View Source
const (
	// BarWidth default bar width
	BarWidth  = 40
	BarFormat = "{@bar} {@percent:4s}%({@current}/{@max}){@message}"
	// SizeFormat size progress bar format. use for file download/upload.
	SizeFormat = "{@bar} {@percent:4s}% {@curSize}/{@maxSize} {@message}"

	// MdlBarFormat more format
	MdlBarFormat  = "{@bar} {@percent:4s}%({@current}/{@max}) {@elapsed:7s}/{@estimated:-7s}"
	FullBarFormat = "{@bar} {@percent:4s}%({@current}/{@max}) {@elapsed:7s}/{@estimated:-7s} {@memory:6s}"
)

internal format for ProgressBar

Variables

View Source
var BarStyles = []BarChars{
	{'=', '>', ' '},
	{'=', '>', '-'},
	{'#', '>', ' '},
	{'#', '>', '-'},
	{'*', '>', '-'},
	{'▉', '▉', '░'},
	{'■', '■', ' '},
	{'■', '■', '▢'},
	{'■', '▶', ' '},
}

BarStyles some built in BarChars style collection

CharThemes collection. can use for Progress bar, RoundTripSpinner

View Source
var CharsThemes = [][]rune{
	{'卍', '卐'},
	{'☺', '☻'},
	{'░', '▒', '▓'},
	{'⊘', '⊖', '⊕', '⊗'},
	{'◐', '◒', '◓', '◑'},
	{'✣', '✤', '✥', '❉'},
	{'-', '\\', '|', '/'},
	{'▢', '■', '▢', '■'},
	[]rune("▖▘▝▗"),
	[]rune("◢◣◤◥"),
	[]rune("⌞⌟⌝⌜"),
	[]rune("◎●◯◌○⊙"),
	[]rune("◡◡⊙⊙◠◠"),
	[]rune("⇦⇧⇨⇩"),
	[]rune("✳✴✵✶✷✸✹"),
	[]rune("←↖↑↗→↘↓↙"),
	[]rune("➩➪➫➬➭➮➯➱"),
	[]rune("①②③④"),
	[]rune("㊎㊍㊌㊋㊏"),
	[]rune("⣾⣽⣻⢿⡿⣟⣯⣷"),
	[]rune("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
	[]rune("▉▊▋▌▍▎▏▎▍▌▋▊▉"),
	[]rune("🌍🌎🌏"),
	[]rune("☰☱☲☳☴☵☶☷"),
	[]rune("⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋"),
	[]rune("🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛"),
}

CharsThemes collection. can use for LoadingBar, LoadingSpinner

Functions

func GetCharTheme

func GetCharTheme(index int) rune

GetCharTheme by index number. if index not exist, will return a random theme

func GetCharsTheme

func GetCharsTheme(index int) []rune

GetCharsTheme by index number

func MaxSteps

func MaxSteps(maxStep int64) func(p *Progress)

MaxSteps setting max steps

func RandomCharTheme

func RandomCharTheme() rune

RandomCharTheme get

func RandomCharsTheme

func RandomCharsTheme() []rune

RandomCharsTheme get

func RenderFormat

func RenderFormat(f string) func(p *Progress)

RenderFormat set rendered format option

Types

type BarChars

type BarChars struct {
	Completed, Processing, Remaining rune
}

BarChars setting for a progress bar. default {'#', '>', ' '}

func RandomBarStyle

func RandomBarStyle() BarChars

RandomBarStyle get random bar style

type BuilderFunc

type BuilderFunc func() string

BuilderFunc build char string

type MultiProgress

type MultiProgress struct {
	Overwrite       bool
	AutoRefresh     bool
	RefreshInterval time.Duration
	Writer          io.Writer
	// contains filtered or unexported fields
}

MultiProgress manages multiple Progress instances and renders them as one block.

func NewMulti

func NewMulti() *MultiProgress

NewMulti creates a new multi progress manager.

Example
buf := new(bytes.Buffer)
mp := NewMulti()
mp.Writer = buf

build := mp.New(3)
build.AddMessage("message", " build")

test := mp.New(2)
test.AddMessage("message", " test")

mp.Start()
build.Advance()
test.Advance()
build.Finish()
test.Finish()
mp.Finish()

func (*MultiProgress) Add

func (mp *MultiProgress) Add(p *Progress) *Progress

Add attaches an existing progress bar to the manager.

func (*MultiProgress) Finish

func (mp *MultiProgress) Finish()

Finish renders the final state and ends the managed block.

func (*MultiProgress) New

func (mp *MultiProgress) New(maxSteps ...int64) *Progress

New creates a managed progress bar.

func (*MultiProgress) Refresh

func (mp *MultiProgress) Refresh()

Refresh re-renders all managed progress bars.

func (*MultiProgress) Start

func (mp *MultiProgress) Start()

Start initializes all registered bars and renders the managed block.

type Progress

type Progress struct {
	// Out output writer. default is cutypes.Output
	Out io.Writer
	// Format string the bar format
	Format string
	// Newline render progress on newline
	Newline bool
	// MaxSteps maximal steps.
	MaxSteps int64
	// StepWidth the width for display "{@current}". default 0 means auto.
	// eg: 342 计数场景,StepWidth = 3. 用于计算填充空格宽度
	StepWidth uint8
	// Overwrite prev output. default is True
	Overwrite bool
	// RedrawFreq redraw freq. default is 1
	RedrawFreq uint
	// Widgets for build the progress bar
	Widgets map[string]WidgetFunc
	// Messages named messages for build progress bar
	// Example:
	// 	{"msg": "downloading ..."}
	// 	"{@percent}% {@msg}" -> "83% downloading ..."
	Messages map[string]string
	// contains filtered or unexported fields
}

Progress definition Refer:

https://github.com/inhere/php-console/blob/master/src/utils/ProgressBar.php

func Bar

func Bar(maxSteps ...int64) *Progress

Bar create a default progress bar. Preview:

	1 [->--------------------------]
	3 [■■■>------------------------]
25/50 [==============>-------------]  50%
Example
maxStep := 105
p := CustomBar(60, BarStyles[0], int64(maxStep))
p.MaxSteps = int64(maxStep)
p.Format = FullBarFormat

p.Start()
for i := 0; i < maxStep; i++ {
	time.Sleep(80 * time.Millisecond)
	p.Advance()
}
p.Finish()

func Counter

func Counter(maxSteps ...int64) *Progress

Counter progress bar create

func CustomBar

func CustomBar(width int, cs BarChars, maxSteps ...int64) *Progress

CustomBar create a custom progress bar.

func DynamicText

func DynamicText(messages map[int]string, maxSteps ...int64) *Progress

DynamicText progress bar create

Example
messages := map[int]string{
	// key is percent, range is 0 - 100.
	20:  " Prepare ...",
	40:  " Request ...",
	65:  " Transport ...",
	95:  " Saving ...",
	100: " Handle Complete.",
}

maxStep := 105
p := DynamicText(messages, int64(maxStep))

p.Start()

for i := 0; i < maxStep; i++ {
	time.Sleep(80 * time.Millisecond)
	p.Advance()
}

p.Finish()

func Full

func Full(maxSteps ...int64) *Progress

Full text progress bar create.

func LoadBar

func LoadBar(chars []rune, maxSteps ...int64) *Progress

LoadBar create loading progress bar

func LoadingBar

func LoadingBar(chars []rune, maxSteps ...int64) *Progress

LoadingBar alias of load bar LoadBar()

func New

func New(maxSteps ...int64) *Progress

New Progress instance

func NewWithConfig

func NewWithConfig(fn func(p *Progress), maxSteps ...int64) *Progress

NewWithConfig create new Progress

func RoundTrip

func RoundTrip(char rune, charNumAndBoxWidth ...int) *Progress

RoundTrip create a RoundTrip progress bar.

Usage:

p := RoundTrip(CharEqual)
// p := RoundTrip('*') // custom char
p.Start()
....
p.Finish()

func RoundTripBar

func RoundTripBar(char rune, charNumAndBoxWidth ...int) *Progress

RoundTripBar alias of RoundTrip()

func SpinnerBar

func SpinnerBar(chars []rune, maxSteps ...int64) *Progress

SpinnerBar alias of load bar LoadBar()

func Tape

func Tape(maxSteps ...int64) *Progress

Tape create new tape progress bar. is alias of Bar()

func Txt

func Txt(maxSteps ...int64) *Progress

Txt progress bar create.

func (*Progress) AddMessage

func (p *Progress) AddMessage(name, message string)

AddMessage to progress instance

func (*Progress) AddMessages

func (p *Progress) AddMessages(msgMap map[string]string)

AddMessages to progress instance

func (*Progress) AddWidget

func (p *Progress) AddWidget(name string, handler WidgetFunc) *Progress

AddWidget to progress instance

func (*Progress) AddWidgets

func (p *Progress) AddWidgets(widgets map[string]WidgetFunc)

AddWidgets to progress instance

func (*Progress) Advance

func (p *Progress) Advance(steps ...int64)

Advance specified step size. default is 1

func (*Progress) AdvanceTo

func (p *Progress) AdvanceTo(step int64)

AdvanceTo specified number of steps

func (*Progress) Binding

func (p *Progress) Binding(data any) *Progress

Binding user custom data to instance

func (*Progress) Bound

func (p *Progress) Bound() any

Bound get bound sub struct instance

func (*Progress) Config

func (p *Progress) Config(fn func(p *Progress)) *Progress

Config the progress instance

func (*Progress) Destroy

func (p *Progress) Destroy()

Destroy removes the progress bar from the current line.

This is useful if you wish to write some output while a progress bar is running. Call display() to show the progress bar again.

func (*Progress) Display

func (p *Progress) Display()

Display outputs the current progress string.

func (*Progress) Finish

func (p *Progress) Finish(message ...string)

Finish the progress output. if provide finish message, will delete progress bar then print the message.

func (*Progress) FinishedAt

func (p *Progress) FinishedAt() time.Time

FinishedAt time get

func (*Progress) Handler

func (p *Progress) Handler(name string) WidgetFunc

Handler get widget handler by widget name

func (*Progress) Line

func (p *Progress) Line() string

Line returns the current rendered progress line.

func (*Progress) Percent

func (p *Progress) Percent() float32

Percent gets the current percent

func (*Progress) Progress

func (p *Progress) Progress() int64

Progress alias of the Step()

func (*Progress) SetWidget

func (p *Progress) SetWidget(name string, handler WidgetFunc) *Progress

SetWidget to progress instance

func (*Progress) Start

func (p *Progress) Start(maxSteps ...int64)

Start the progress bar

func (*Progress) StartedAt

func (p *Progress) StartedAt() time.Time

StartedAt time get

func (*Progress) Step

func (p *Progress) Step() int64

Step gets the current step position.

func (*Progress) WithMaxSteps

func (p *Progress) WithMaxSteps(maxSteps ...int64) *Progress

WithMaxSteps setting max steps

func (*Progress) WithOptions

func (p *Progress) WithOptions(fns ...func(p *Progress)) *Progress

WithOptions add more option at once for the progress instance

func (*Progress) WrapReader added in v0.2.2

func (p *Progress) WrapReader(r io.Reader) io.Reader

WrapReader wraps r and advances the progress by each successful read count.

func (*Progress) WrapWriter added in v0.2.2

func (p *Progress) WrapWriter(w io.Writer) io.Writer

WrapWriter wraps w and advances the progress by each successful write count.

func (*Progress) Write added in v0.2.2

func (p *Progress) Write(bs []byte) (int, error)

Write advances the progress by the number of bytes in bs.

type Progresser

type Progresser interface {
	Start(maxSteps ...int64)
	Advance(steps ...int64)
	AdvanceTo(step int64)
	Finish(msg ...string)
	Bound() any
}

Progresser progress interface

type RoundTripOptions added in v0.2.1

type RoundTripOptions struct {
	Char  rune
	Speed time.Duration
	CharN int // char number
	BoxW  int // box width
}

RoundTripOptions for create Round-Trip Spinner

type SpinnerFactory

type SpinnerFactory struct {
	// Out output writer. default is cutypes.Output
	Out io.Writer
	// Speed is the running speed
	Speed time.Duration
	// Format setting display format
	Format string
	// Builder build custom spinner text
	Builder BuilderFunc
	// contains filtered or unexported fields
}

SpinnerFactory definition. ref https://github.com/briandowns/spinner

func LoadingSpinner

func LoadingSpinner(chars []rune, speed time.Duration) *SpinnerFactory

LoadingSpinner instance create. 多个字符不停的变化,显示出旋转的效果

Example
s := LoadingSpinner(RandomCharsTheme(), 100*time.Millisecond)

s.Start("%s work handling ... ...")
// Run for some time to simulate work
time.Sleep(4 * time.Second)
s.Stop("work handle complete")

func RoundTripLoading

func RoundTripLoading(char rune, speed time.Duration, charNumAndBoxWidth ...int) *SpinnerFactory

RoundTripLoading create. alias of RoundTripSpinner

func RoundTripSpinner

func RoundTripSpinner(char rune, speed time.Duration, charNumAndBoxWidth ...int) *SpinnerFactory

RoundTripSpinner instance create. eg: [ = ] - 字符在盒子里来回移动

Example
s := RoundTripSpinner(RandomCharTheme(), 100*time.Millisecond)

s.Start("%s work handling ... ...")
// Run for some time to simulate work
time.Sleep(4 * time.Second)
s.Stop("work handle complete")

func Spinner

func Spinner(speed time.Duration) *SpinnerFactory

Spinner instance

func SpinnerLoading added in v0.2.1

func SpinnerLoading(speed ...time.Duration) *SpinnerFactory

SpinnerLoading quickly create a loading spinner instance.

func SpinnerRoundTrip added in v0.2.1

func SpinnerRoundTrip(optFns ...func(opts *RoundTripOptions)) *SpinnerFactory

SpinnerRoundTrip quickly create a Round-Trip Spinner instance.

func (*SpinnerFactory) Active

func (s *SpinnerFactory) Active() bool

Active status

func (*SpinnerFactory) Restart

func (s *SpinnerFactory) Restart()

Restart will stop and start the spinner

func (*SpinnerFactory) Start

func (s *SpinnerFactory) Start(format ...string)

Start run spinner

func (*SpinnerFactory) Stop

func (s *SpinnerFactory) Stop(finalMsg ...string)

Stop run spinner

func (*SpinnerFactory) WithBuilder

func (s *SpinnerFactory) WithBuilder(builder BuilderFunc) *SpinnerFactory

WithBuilder set spinner text builder

type WidgetFunc

type WidgetFunc func(p *Progress) string

WidgetFunc handler func for progress widget

func BarWidget

func BarWidget(width int, cs BarChars) WidgetFunc

BarWidget create a progress bar widget.

Output like `[==============>-------------]`

func DynamicTextWidget

func DynamicTextWidget(messages map[int]string) WidgetFunc

DynamicTextWidget dynamic text message widget for progress bar. for param messages: int is percent, range is 0 - 100. value is message string. Usage please example.

func LoadingWidget

func LoadingWidget(chars []rune) WidgetFunc

LoadingWidget create loading progress widget

func RoundTripWidget

func RoundTripWidget(char rune, charNum, boxWidth int) WidgetFunc

RoundTripWidget create a round-trip widget for progress bar.

Output like `[ ==== ]`

Jump to

Keyboard shortcuts

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