progress

package
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 14 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` ...

Concurrency: Progress and MultiProgress are NOT safe for concurrent use by multiple goroutines. For a managed bar, update it through its MultiProgress (Advance, SetMessage, Reset, ...) from a single goroutine; do not call Progress methods directly from several goroutines at once.

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

View Source
const DefaultByteTrackerInterval = 100 * time.Millisecond

DefaultByteTrackerInterval is used when a ByteTracker interval is not set.

View Source
const DefaultRefreshInterval = 100 * time.Millisecond

DefaultRefreshInterval is used when MultiProgress auto refresh is enabled and RefreshInterval is not set.

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 IsTerminal added in v0.3.0

func IsTerminal(w io.Writer) bool

IsTerminal reports whether w is an interactive terminal.

It accepts *os.File as well as any writer exposing an Fd() method, so a wrapped writer (e.g. a color writer) is still recognized.

func MaxSteps

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

MaxSteps setting max steps

func NewConcurrentWriter added in v0.3.0

func NewConcurrentWriter(p *Progress) io.Writer

NewConcurrentWriter creates a writer that tracks written byte counts.

func NewConcurrentWriterWithInterval added in v0.3.0

func NewConcurrentWriterWithInterval(p *Progress, interval time.Duration) io.WriteCloser

NewConcurrentWriterWithInterval creates a closeable writer with a custom byte tracking flush interval.

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 ByteTracker added in v0.3.0

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

ByteTracker aggregates byte progress updates and periodically flushes them to a Progress instance.

func NewByteTracker added in v0.3.0

func NewByteTracker(p *Progress) *ByteTracker

NewByteTracker creates a byte tracker using DefaultByteTrackerInterval.

func NewByteTrackerWithInterval added in v0.3.0

func NewByteTrackerWithInterval(p *Progress, interval time.Duration) *ByteTracker

NewByteTrackerWithInterval creates a byte tracker with a custom flush interval.

func (*ByteTracker) Add added in v0.3.0

func (t *ByteTracker) Add(n int64)

Add records a byte delta. Non-positive deltas are ignored.

func (*ByteTracker) Close added in v0.3.0

func (t *ByteTracker) Close()

Close stops the tracker and flushes pending bytes.

type FdWriter added in v0.5.0

type FdWriter interface {
	Fd() uintptr
}

FdWriter is implemented by writers that expose a file descriptor.

type MultiProgress

type MultiProgress struct {
	Overwrite       bool
	AutoRefresh     bool
	RefreshInterval time.Duration
	RenderMode      RenderMode
	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) Finished added in v0.3.0

func (mp *MultiProgress) Finished() bool

Finished reports whether the multi progress manager has finished.

func (*MultiProgress) Hide added in v0.3.0

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

Hide hides a managed progress bar without removing it from the manager.

func (*MultiProgress) Len added in v0.3.0

func (mp *MultiProgress) Len() int

Len returns the number of managed progress bars.

func (*MultiProgress) New

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

New creates a managed progress bar.

func (*MultiProgress) Printf added in v0.3.0

func (mp *MultiProgress) Printf(format string, args ...any)

Printf writes formatted text without breaking the managed progress block.

func (*MultiProgress) Println added in v0.3.0

func (mp *MultiProgress) Println(args ...any)

Println writes a line without breaking the managed progress block.

func (*MultiProgress) Refresh

func (mp *MultiProgress) Refresh()

Refresh re-renders all managed progress bars.

func (*MultiProgress) Remove added in v0.3.0

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

Remove removes a progress bar from rendering while keeping it managed so later updates become no-ops instead of standalone output.

func (*MultiProgress) RunExclusive added in v0.3.0

func (mp *MultiProgress) RunExclusive(fn func(w io.Writer))

RunExclusive clears the managed progress block, lets fn write to the manager writer, then redraws the block.

func (*MultiProgress) Show added in v0.3.0

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

Show makes a hidden managed progress bar visible again.

func (*MultiProgress) Start

func (mp *MultiProgress) Start()

Start initializes all registered bars and renders the managed block.

func (*MultiProgress) Started added in v0.3.0

func (mp *MultiProgress) Started() bool

Started reports whether the multi progress manager has started.

func (*MultiProgress) UseAutoRenderMode added in v0.3.0

func (mp *MultiProgress) UseAutoRenderMode()

UseAutoRenderMode selects dynamic rendering for terminals and plain rendering for non-interactive writers.

func (*MultiProgress) VisibleLen added in v0.3.0

func (mp *MultiProgress) VisibleLen() int

VisibleLen returns the number of visible managed progress bars.

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) Done added in v0.3.0

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

Done marks the progress as completed.

func (*Progress) Fail added in v0.3.0

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

Fail marks the progress as failed without advancing it to completion.

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) Finished added in v0.3.0

func (p *Progress) Finished() bool

Finished reports whether the progress has been finished.

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) Max added in v0.3.0

func (p *Progress) Max() int64

Max gets the max steps.

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) Reset added in v0.3.0

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

Reset resets the progress state so the instance can be reused.

func (*Progress) ResetWith added in v0.3.0

func (p *Progress) ResetWith(fn func(p *Progress))

ResetWith resets the progress and applies fn while holding the manager lock when the progress is managed.

func (*Progress) SetFormat added in v0.3.0

func (p *Progress) SetFormat(format string) *Progress

SetFormat updates the progress render format.

func (*Progress) SetMaxSteps added in v0.3.0

func (p *Progress) SetMaxSteps(maxSteps int64) *Progress

SetMaxSteps updates the progress max steps.

func (*Progress) SetMessage added in v0.3.0

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

SetMessage sets a named message and returns the progress instance.

func (*Progress) SetMessages added in v0.3.0

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

SetMessages sets multiple named messages and returns the progress instance.

func (*Progress) SetWidget

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

SetWidget to progress instance

func (*Progress) Skip added in v0.3.0

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

Skip marks the progress as skipped without advancing it to completion.

func (*Progress) Start

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

Start the progress bar

func (*Progress) Started added in v0.3.0

func (p *Progress) Started() bool

Started reports whether the progress has been started.

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 RenderMode added in v0.3.0

type RenderMode int

RenderMode controls how MultiProgress writes progress output.

const (
	// RenderDynamic renders a managed ANSI block.
	RenderDynamic RenderMode = iota
	// RenderPlain renders plain progress lines without ANSI block controls.
	RenderPlain
	// RenderDisabled disables progress rendering.
	RenderDisabled
)

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