Documentation
¶
Overview ¶
Package mpb 是 Rust 进度条库 indicatif 的 Go 移植。
来源 ¶
上游仓库 github.com/console-rs/indicatif,对齐的版本是 0.18.6 (commit 3adb05c80429415743d8142503c24fa8ee639453)。 移植的原则是**逐语义对齐**而不是逐语法翻译:同样的模板语法、同样的宽度与 换行度量、同样的僵尸行(zombie)算法、同样的绘制限速。Rust 的枚举与 trait 在 Go 里落成接口与结构体字段,但行为保持一致。
模块 ¶
style.go 模板与样式({bar:40.red/blue}、on_* 背景色、256 色、真彩色、宽度度量)
state.go 进度条状态、绘制状态与出帧
draw_target.go 绘制目标(终端 / term-like / multi / hidden)、限速、行数调整
multi.go MultiProgress / MultiState、成员排序、orphan 行、僵尸行
progress_bar.go ProgressBar 门面
iter.go 迭代器包装(rayon.go 提供并行版)
format.go HumanBytes / HumanDuration / HumanFloatCount 等格式化
in_memory.go 内存终端,测试用
term_like.go 终端抽象
用法 ¶
单条进度条:
pb := mpb.New(100)
pb.SetStyle(mpb.DefaultProgressStyleBar())
for i := 0; i < 100; i++ {
pb.Inc(1)
time.Sleep(10 * time.Millisecond)
}
pb.Finish()
多条进度条:
mp := mpb.NewMultiProgress() pb1 := mp.Add(mpb.New(100)) pb2 := mp.Add(mpb.New(200))
两个容易踩的点 ¶
- 绘制目标默认是 stderr。按上游语义,stderr 不是真终端(重定向到文件或 管道)时整条进度条会隐藏 —— 见 ProgressDrawTarget.IsHidden。测试里要拿 渲染结果请用 NewInMemoryTerm 配 NewInMemoryDrawTarget。
- ProgressBar.Index 返回的是 MultiState 里**不透明**的槽位下标(会被复用), 要「屏幕上是第几行」请用 ProgressBar.VisualIndex。
Index ¶
- Constants
- Variables
- func MapParallel[T any, U any](p *ProgressBarIter[T], workers int, fn func(T) U) []U
- type AtomicPosition
- type BarState
- func (b *BarState) DecLength(now time.Time, delta uint64)
- func (b *BarState) FinishUsingStyle(now time.Time, finish ProgressFinish)
- func (b *BarState) IncLength(now time.Time, delta uint64)
- func (b *BarState) Index() (uint, bool)
- func (b *BarState) Println(now time.Time, msg string)
- func (b *BarState) Reset(now time.Time, mode ResetMode)
- func (b *BarState) SetLength(now time.Time, l uint64)
- func (b *BarState) SetStyle(style ProgressStyle)
- func (b *BarState) SetTabWidth(tabWidth int)
- func (b *BarState) Suspend(now time.Time, f func() interface{}) interface{}
- func (b *BarState) Tick(now time.Time)
- func (b *BarState) UnsetLength(now time.Time)
- func (b *BarState) Update(now time.Time, f func(*ProgressState), tick bool)
- func (b *BarState) UpdateEstimateAndDraw(now time.Time)
- type BinaryBytes
- type DecimalBytes
- type DrawState
- type DrawStateStub
- type DrawStateWrapper
- type Drawable
- type DrawableStub
- type Estimator
- type FinishKind
- type FormattedDuration
- type HumanBytes
- type HumanCount
- type HumanDuration
- type HumanFloatCount
- type InMemoryTerm
- func (t *InMemoryTerm) ClearLine() error
- func (t *InMemoryTerm) Contents() string
- func (t *InMemoryTerm) ContentsFormatted() []byte
- func (t *InMemoryTerm) Flush() error
- func (t *InMemoryTerm) Height() uint16
- func (t *InMemoryTerm) MoveCursorDown(n int) error
- func (t *InMemoryTerm) MoveCursorLeft(n int) error
- func (t *InMemoryTerm) MoveCursorRight(n int) error
- func (t *InMemoryTerm) MoveCursorUp(n int) error
- func (t *InMemoryTerm) MovesSinceLastCheck() string
- func (t *InMemoryTerm) Reset()
- func (t *InMemoryTerm) Width() uint16
- func (t *InMemoryTerm) WriteLine(s string) error
- func (t *InMemoryTerm) WriteStr(s string) error
- type InsertLocation
- type LineAdjust
- type LineAdjustKind
- type LineType
- type MultiProgress
- func (mp *MultiProgress) Add(pb *ProgressBar) *ProgressBar
- func (mp *MultiProgress) Clear() error
- func (mp *MultiProgress) Insert(index uint, pb *ProgressBar) *ProgressBar
- func (mp *MultiProgress) InsertAfter(after *ProgressBar, pb *ProgressBar) *ProgressBar
- func (mp *MultiProgress) InsertBefore(before *ProgressBar, pb *ProgressBar) *ProgressBar
- func (mp *MultiProgress) InsertFromBack(index uint, pb *ProgressBar) *ProgressBar
- func (mp *MultiProgress) IsHidden() bool
- func (mp *MultiProgress) New() *MultiProgress
- func (mp *MultiProgress) Println(msg string) error
- func (mp *MultiProgress) Remove(pb *ProgressBar)
- func (mp *MultiProgress) SetAlignment(alignment MultiProgressAlignment)
- func (mp *MultiProgress) SetDrawTarget(target ProgressDrawTarget)
- func (mp *MultiProgress) SetMoveCursor(moveCursor bool)
- func (mp *MultiProgress) Suspend(f func() interface{}) interface{}
- func (mp *MultiProgress) WithDrawTarget(dt ProgressDrawTarget) *MultiProgress
- type MultiProgressAlignment
- type MultiState
- type MultiStateMember
- type MultiStateStub
- type ProgressBar
- func (p *ProgressBar) Abandon()
- func (p *ProgressBar) AbandonWithMessage(msg string)
- func (p *ProgressBar) Clone() *ProgressBar
- func (p *ProgressBar) Dec(delta uint64)
- func (p *ProgressBar) DecLength(delta uint64)
- func (p *ProgressBar) DisableSteadyTick()
- func (p *ProgressBar) Downgrade() WeakProgressBar
- func (p *ProgressBar) Duration() time.Duration
- func (p *ProgressBar) Elapsed() time.Duration
- func (p *ProgressBar) EnableSteadyTick(interval time.Duration)
- func (p *ProgressBar) Eta() time.Duration
- func (p *ProgressBar) Finish()
- func (p *ProgressBar) FinishAndClear()
- func (p *ProgressBar) FinishUsingStyle()
- func (p *ProgressBar) FinishWithMessage(msg string)
- func (p *ProgressBar) ForceDraw()
- func (p *ProgressBar) Inc(delta uint64)
- func (p *ProgressBar) IncLength(delta uint64)
- func (p *ProgressBar) Index() (uint, bool)
- func (p *ProgressBar) IsFinished() bool
- func (p *ProgressBar) IsHidden() bool
- func (p *ProgressBar) Length() *uint64
- func (p *ProgressBar) Message() string
- func (p *ProgressBar) PerSec() float64
- func (p *ProgressBar) Position() uint64
- func (p *ProgressBar) Prefix() string
- func (p *ProgressBar) Println(msg string)
- func (p *ProgressBar) Reset()
- func (p *ProgressBar) ResetElapsed()
- func (p *ProgressBar) ResetEta()
- func (p *ProgressBar) SetDrawTarget(dt ProgressDrawTarget)
- func (p *ProgressBar) SetElapsed(elapsed time.Duration)
- func (p *ProgressBar) SetLength(l uint64)
- func (p *ProgressBar) SetMessage(msg string)
- func (p *ProgressBar) SetPosition(pos uint64)
- func (p *ProgressBar) SetPrefix(prefix string)
- func (p *ProgressBar) SetStyle(style ProgressStyle)
- func (p *ProgressBar) SetTabWidth(w int)
- func (p *ProgressBar) Style() ProgressStyle
- func (p *ProgressBar) Suspend(f func() interface{}) interface{}
- func (p *ProgressBar) TabWidth() int
- func (p *ProgressBar) UnsetLength()
- func (p *ProgressBar) Update(f func(*ProgressState))
- func (p *ProgressBar) VisualIndex() (uint, bool)
- func (p *ProgressBar) WithElapsed(d time.Duration) *ProgressBar
- func (p *ProgressBar) WithFinish(f ProgressFinish) *ProgressBar
- func (p *ProgressBar) WithMessage(msg string) *ProgressBar
- func (p *ProgressBar) WithPosition(pos uint64) *ProgressBar
- func (p *ProgressBar) WithPrefix(prefix string) *ProgressBar
- func (p *ProgressBar) WithStyle(style ProgressStyle) *ProgressBar
- func (p *ProgressBar) WithTabWidth(w int) *ProgressBar
- func (p *ProgressBar) WrapRead(r io.Reader) io.Reader
- func (p *ProgressBar) WrapWrite(w io.Writer) io.Writer
- type ProgressBarIter
- func NewProgressBarIterFromSlice[T any](slice []T, pb *ProgressBar) *ProgressBarIter[T]
- func Progress[T any](slice []T) *ProgressBarIter[T]
- func ProgressCount[T any](slice []T, count uint64) *ProgressBarIter[T]
- func ProgressWithSlice[T any](slice []T, pb *ProgressBar) *ProgressBarIter[T]
- func ProgressWithStyle[T any](slice []T, style ProgressStyle) *ProgressBarIter[T]
- func TryProgress[T any](slice []T) (*ProgressBarIter[T], bool)
- func WrapSlice[T any](p *ProgressBar, slice []T) *ProgressBarIter[T]
- func (p *ProgressBarIter[T]) Len() int
- func (p *ProgressBarIter[T]) Next() (T, bool)
- func (p *ProgressBarIter[T]) NextBack() (T, bool)
- func (p *ProgressBarIter[T]) WithElapsed(elapsed time.Duration) *ProgressBarIter[T]
- func (p *ProgressBarIter[T]) WithFinish(f ProgressFinish) *ProgressBarIter[T]
- func (p *ProgressBarIter[T]) WithMessage(msg string) *ProgressBarIter[T]
- func (p *ProgressBarIter[T]) WithPosition(pos uint64) *ProgressBarIter[T]
- func (p *ProgressBarIter[T]) WithPrefix(prefix string) *ProgressBarIter[T]
- func (p *ProgressBarIter[T]) WithStyle(style ProgressStyle) *ProgressBarIter[T]
- type ProgressDrawTarget
- func NewHiddenDrawTarget() ProgressDrawTarget
- func NewInMemoryDrawTarget(t *InMemoryTerm) ProgressDrawTarget
- func NewRemoteDrawTarget(ms *MultiState, idx uint) ProgressDrawTarget
- func NewStderrDrawTarget() ProgressDrawTarget
- func NewStderrDrawTargetWithHz(refreshRate uint8) ProgressDrawTarget
- func NewStdoutDrawTarget() ProgressDrawTarget
- func NewStdoutDrawTargetWithHz(refreshRate uint8) ProgressDrawTarget
- func NewTermDrawTarget(term TermLike, refreshRate uint8) ProgressDrawTarget
- func NewTermLikeDrawTarget(termLike TermLike) ProgressDrawTarget
- func NewTermLikeDrawTargetWithHz(termLike TermLike, refreshRate uint8) ProgressDrawTarget
- type ProgressFinish
- type ProgressReaderIter
- type ProgressState
- func (ps *ProgressState) Duration() time.Duration
- func (ps *ProgressState) Elapsed() time.Duration
- func (ps *ProgressState) Eta() time.Duration
- func (ps *ProgressState) Fraction() float32
- func (ps *ProgressState) IsFinished() bool
- func (ps *ProgressState) Len() *uint64
- func (ps *ProgressState) PerSec() float64
- func (ps *ProgressState) Pos() uint64
- func (ps *ProgressState) SetLen(v uint64)
- func (ps *ProgressState) SetPos(v uint64)
- type ProgressStyle
- func (ps *ProgressStyle) FormatState(state *ProgressState, targetWidth int, forStderr bool) ([]LineType, []string)
- func (ps ProgressStyle) ProgressChars(s string) ProgressStyle
- func (ps *ProgressStyle) SetForStderr()
- func (ps *ProgressStyle) SetProgressChars(s string)
- func (ps *ProgressStyle) SetTabWidth(w int)
- func (ps ProgressStyle) Template(s string) (ProgressStyle, error)
- func (ps ProgressStyle) TickChars(s string) ProgressStyle
- func (ps ProgressStyle) TickStrings(ss []string) ProgressStyle
- func (ps *ProgressStyle) WithKey(key string, f func(*ProgressState) string)
- func (ps *ProgressStyle) WithKeyStyle(key string, f func(*ProgressState, bool) (string, *Style))
- func (ps *ProgressStyle) WithTracker(key string, t ProgressTracker)
- type ProgressTracker
- type ProgressWriterIter
- type RateLimiter
- type RemoteStub
- type ResetMode
- type SafeBarState
- func (s *SafeBarState) DecLength(now time.Time, d uint64)
- func (s *SafeBarState) Draw(force bool) error
- func (s *SafeBarState) DrawWithNow(force bool, now time.Time) error
- func (s *SafeBarState) Duration() time.Duration
- func (s *SafeBarState) Elapsed() time.Duration
- func (s *SafeBarState) Eta() time.Duration
- func (s *SafeBarState) FinishUsingStyle(now time.Time, f ProgressFinish)
- func (s *SafeBarState) FormatForWidth(width int) ([]LineType, []string)
- func (s *SafeBarState) GetOnFinish() ProgressFinish
- func (s *SafeBarState) IncLength(now time.Time, d uint64)
- func (s *SafeBarState) Index() (uint, bool)
- func (s *SafeBarState) IsFinished() bool
- func (s *SafeBarState) IsHidden() bool
- func (s *SafeBarState) Len() *uint64
- func (s *SafeBarState) Message() string
- func (s *SafeBarState) PerSec() float64
- func (s *SafeBarState) Pos() uint64
- func (s *SafeBarState) Position() uint64
- func (s *SafeBarState) Prefix() string
- func (s *SafeBarState) Println(now time.Time, msg string)
- func (s *SafeBarState) Reset(now time.Time, mode ResetMode)
- func (s *SafeBarState) SetDrawTarget(dt ProgressDrawTarget)
- func (s *SafeBarState) SetElapsed(d time.Duration)
- func (s *SafeBarState) SetLength(now time.Time, l uint64)
- func (s *SafeBarState) SetMessage(msg string)
- func (s *SafeBarState) SetOnFinish(f ProgressFinish)
- func (s *SafeBarState) SetPos(v uint64)
- func (s *SafeBarState) SetPrefix(prefix string)
- func (s *SafeBarState) SetStyle(style ProgressStyle)
- func (s *SafeBarState) SetTabWidth(w int)
- func (s *SafeBarState) Style() ProgressStyle
- func (s *SafeBarState) Suspend(now time.Time, f func() interface{}) interface{}
- func (s *SafeBarState) TabWidth() int
- func (s *SafeBarState) Tick(now time.Time)
- func (s *SafeBarState) UnsetLength(now time.Time)
- func (s *SafeBarState) Update(now time.Time, f func(*ProgressState), tick bool)
- func (s *SafeBarState) VisualIndex() (uint, bool)
- type SeekMax
- type Status
- type StatusKind
- type StdTerm
- func (t *StdTerm) ClearLine() error
- func (t *StdTerm) Flush() error
- func (t *StdTerm) Height() uint16
- func (t *StdTerm) IsTerm() bool
- func (t *StdTerm) MoveCursorDown(n int) error
- func (t *StdTerm) MoveCursorLeft(n int) error
- func (t *StdTerm) MoveCursorRight(n int) error
- func (t *StdTerm) MoveCursorUp(n int) error
- func (t *StdTerm) Width() uint16
- func (t *StdTerm) WriteLine(s string) error
- func (t *StdTerm) WriteStr(s string) error
- type Style
- type TabExpandedString
- type Template
- type TemplateError
- type TemplatePart
- type TermLike
- type TickerHandle
- type VisualLines
- type WeakProgressBar
- type Width
Constants ¶
const DEFAULT_TAB_WIDTH = 8
Variables ¶
var ( SECOND = time.Second MINUTE = time.Minute HOUR = time.Hour DAY = 24 * HOUR WEEK = 7 * DAY YEAR = 365 * DAY )
时间单位常量
var DefaultWidth = Width{}
DefaultWidth 对应 Rust 的 `pub(crate) static WIDTH: Width = Width::new()`。
Functions ¶
func MapParallel ¶
func MapParallel[T any, U any](p *ProgressBarIter[T], workers int, fn func(T) U) []U
MapParallel 对应 Rust 里对包装后的并行迭代器做 `map(...).collect()`:
- 与 ProgressFolder::consume 一致:每消费一个元素 inc(1)(先推进再干活);
- 与 IndexedParallelIterator 的 collect 一致:**结果按输入顺序排列** (原来的实现从 out channel 里先到先收,顺序是乱的);
- 与 Rust 一致:消费完不收尾进度条(Folder::complete 只 complete 底层, 不调 finish;是否收尾由调用方决定);
- 迭代器被消费掉(Rust 的 drive 取得所有权),消费后 Len() 为 0。
workers 对应 rayon 的分片并发度:Rust 那边由全局线程池决定,Go 这里显式给。
Types ¶
type AtomicPosition ¶
type AtomicPosition struct {
// contains filtered or unexported fields
}
AtomicPosition 是对 Rust 中 AtomicPosition 的复现。 它包含位置计数、令牌桶(capacity)、上次允许时间(prev)和起始时间(start)。
func NewAtomicPosition ¶
func NewAtomicPosition() *AtomicPosition
func (*AtomicPosition) Allow ¶
func (a *AtomicPosition) Allow(now time.Time) bool
Allow 模拟 Rust 的 allow() 行为:基于时间窗为 tick 决定是否允许。
func (*AtomicPosition) Dec ¶
func (a *AtomicPosition) Dec(delta uint64)
func (*AtomicPosition) Inc ¶
func (a *AtomicPosition) Inc(delta uint64)
func (*AtomicPosition) Pos ¶
func (a *AtomicPosition) Pos() uint64
func (*AtomicPosition) Reset ¶
func (a *AtomicPosition) Reset(now time.Time)
func (*AtomicPosition) Set ¶
func (a *AtomicPosition) Set(v uint64)
type BarState ¶
type BarState struct {
// contains filtered or unexported fields
}
BarState 对应 Rust 的 BarState
func NewBarState ¶
func NewBarState(len *uint64, drawTarget ProgressDrawTarget, pos *AtomicPosition) *BarState
NewBarState 创建 BarState,接受 pos(AtomicPosition)以与 Rust 保持一致
func (*BarState) FinishUsingStyle ¶
func (b *BarState) FinishUsingStyle(now time.Time, finish ProgressFinish)
FinishUsingStyle 完成时应用样式行为
func (*BarState) Index ¶
Index 返回进度条在 MultiProgress 中的索引(如果存在)。
对应 Rust 的 `ProgressBar::index() -> Option<MultiStateIndex>`:不透明下标,类型是 usize(Go 侧即 uint),与屏幕位置无关 —— 要看第几行用 VisualIndex()。
func (*BarState) SetStyle ¶
func (b *BarState) SetStyle(style ProgressStyle)
func (*BarState) SetTabWidth ¶
func (*BarState) UnsetLength ¶
func (*BarState) Update ¶
func (b *BarState) Update(now time.Time, f func(*ProgressState), tick bool)
Update 更新内部 ProgressState 并在需要时 tick
func (*BarState) UpdateEstimateAndDraw ¶
type BinaryBytes ¶
type BinaryBytes uint64
BinaryBytes: 使用二进制前缀显示 (KiB, MiB)
func (BinaryBytes) String ¶
func (b BinaryBytes) String() string
type DecimalBytes ¶
type DecimalBytes uint64
DecimalBytes: 使用十进制 SI 前缀 (kB, MB)
func (DecimalBytes) String ¶
func (b DecimalBytes) String() string
type DrawState ¶
type DrawState struct {
// contains filtered or unexported fields
}
draw target 的具体实现位于 draw_target.go(增量翻译)。 DrawState mirrors Rust's DrawState: it holds the lines to print, the move_cursor flag and the alignment for multi progress.
type DrawStateStub ¶
type DrawStateStub = DrawState
Keep DrawStateStub as an alias for compatibility where referenced.
type DrawStateWrapper ¶
type DrawStateWrapper struct {
StatePtr *DrawStateStub
// contains filtered or unexported fields
}
DrawStateWrapper is a RAII-style wrapper around DrawStateStub used to emulate Rust's DrawStateWrapper behavior: when Close() is called and an orphanLines slice was provided, non-bar lines are moved into orphanLines.
func DrawStateWrapperForMulti ¶
func DrawStateWrapperForMulti(s *DrawStateStub, orphan *[]string) *DrawStateWrapper
func DrawStateWrapperForTerm ¶
func DrawStateWrapperForTerm(s *DrawStateStub) *DrawStateWrapper
func (*DrawStateWrapper) Close ¶
func (w *DrawStateWrapper) Close()
Close 对应 Rust 的 `impl Drop for DrawStateWrapper`: 只有 orphan_lines 为 Some(即 multi 路径)时才把 Text/Empty 行移出去; term 路径下这些行要留在 state 里照常绘制 —— 否则 Println 的消息会被整段丢掉。
func (*DrawStateWrapper) Reset ¶
func (w *DrawStateWrapper) Reset()
type Drawable ¶
type Drawable interface {
State() *DrawStateWrapper
Draw() error
Clear() error
Width() *uint16
}
type DrawableStub ¶
type DrawableStub interface {
State() *DrawStateStub
Draw() error
Clear() error
}
type Estimator ¶
type Estimator struct {
// contains filtered or unexported fields
}
func NewEstimator ¶
type FinishKind ¶
type FinishKind int
ProgressFinish 表示完成时的行为(对应 Rust 的 enum)
const ( FinishAndLeave FinishKind = iota FinishWithMessage FinishAndClear FinishAbandon FinishAbandonWithMessage )
type FormattedDuration ¶
FormattedDuration: 包装 time.Duration 用于基本人类可读格式化
func (FormattedDuration) String ¶
func (d FormattedDuration) String() string
type HumanBytes ¶
type HumanBytes uint64
HumanBytes: 把字节数格式化为人类可读(使用二进制前缀,KiB 等)
func (HumanBytes) String ¶
func (b HumanBytes) String() string
type HumanCount ¶
type HumanCount uint64
HumanCount: 使用千位分隔符格式化整数
func (HumanCount) String ¶
func (h HumanCount) String() string
type HumanDuration ¶
HumanDuration: 包装 time.Duration 用于更直观的人类可读显示
func (HumanDuration) Format ¶
func (d HumanDuration) Format(s fmt.State, verb rune)
为 fmt.Formatter 的兼容性提供支持(便于处理 %#v 等)
func (HumanDuration) String ¶
func (d HumanDuration) String() string
type InMemoryTerm ¶
type InMemoryTerm struct {
// contains filtered or unexported fields
}
InMemoryTerm 是一个轻量的内存终端实现(对应 src/in_memory.rs)。
Rust 那边是 `Arc<Mutex<InMemoryTermState>>`("so it can be freely cloned"), Go 里 state 是指针,*InMemoryTerm 之间天然共享同一份 state,语义等价。
func NewInMemoryTerm ¶
func NewInMemoryTerm(rows uint16, cols uint16) *InMemoryTerm
NewInMemoryTerm 使用指定的行数和列数创建一个新的内存终端(Rust 里 rows/cols 必须 > 0)。
func (*InMemoryTerm) ClearLine ¶
func (t *InMemoryTerm) ClearLine() error
func (*InMemoryTerm) Contents ¶
func (t *InMemoryTerm) Contents() string
Contents 返回当前屏幕的文本内容(去掉行尾空白,并去掉尾部空行)。
对应 Rust 的 contents():rev().skip_while(空).map(trim_end).rev().join("\n")。 注意顺序:Rust 那边 vt100 的 `screen().rows(..)` 返回的行本身就不带尾部空格,所以「判空」和 「trim」孰先孰后都一样;Go 的 buf 是空格填充的,必须先 trim 再判空,否则尾部空行会被当成非空。
func (*InMemoryTerm) ContentsFormatted ¶
func (t *InMemoryTerm) ContentsFormatted() []byte
ContentsFormatted 返回每行后面附加重置 ANSI 序列的字节表示。 与 Rust 一致:先去掉尾部空行,再给每行拼 "\x1b[m" + '\n',最后砍掉末尾那个 '\n' (保留末尾的 reset)。
func (*InMemoryTerm) Flush ¶
func (t *InMemoryTerm) Flush() error
func (*InMemoryTerm) Height ¶
func (t *InMemoryTerm) Height() uint16
func (*InMemoryTerm) MoveCursorDown ¶
func (t *InMemoryTerm) MoveCursorDown(n int) error
func (*InMemoryTerm) MoveCursorLeft ¶
func (t *InMemoryTerm) MoveCursorLeft(n int) error
func (*InMemoryTerm) MoveCursorRight ¶
func (t *InMemoryTerm) MoveCursorRight(n int) error
func (*InMemoryTerm) MoveCursorUp ¶
func (t *InMemoryTerm) MoveCursorUp(n int) error
func (*InMemoryTerm) MovesSinceLastCheck ¶
func (t *InMemoryTerm) MovesSinceLastCheck() string
MovesSinceLastCheck 返回自上次检查以来的移动历史(并清空历史)。 与 Rust 一致:对每条 Move 用 `writeln!(s, "{line:?}")` 打印,即 Debug 格式。
func (*InMemoryTerm) Reset ¶
func (t *InMemoryTerm) Reset()
Reset 重置终端内容为初始状态。 对应 Rust 的 `*state = InMemoryTermState::new(..)`:改的是共享的 state 本体, 所以所有共享该 state 的 InMemoryTerm 都能看到重置(不是只换自己那根指针)。
func (*InMemoryTerm) Width ¶
func (t *InMemoryTerm) Width() uint16
func (*InMemoryTerm) WriteLine ¶
func (t *InMemoryTerm) WriteLine(s string) error
func (*InMemoryTerm) WriteStr ¶
func (t *InMemoryTerm) WriteStr(s string) error
type InsertLocation ¶
type InsertLocation int
const ( InsertLocationEnd InsertLocation = iota InsertLocationIndex InsertLocationIndexFromBack InsertLocationAfter InsertLocationBefore )
type LineAdjust ¶
type LineAdjust struct {
Kind LineAdjustKind
Count VisualLines
}
type LineAdjustKind ¶
type LineAdjustKind int
const ( LineAdjustClear LineAdjustKind = iota LineAdjustKeep )
type LineType ¶
type LineType int
func LineEmptyVal ¶
func LineEmptyVal() LineType
func LineTextVal ¶
type MultiProgress ¶
type MultiProgress struct {
State *MultiState
}
MultiProgress 对应 Rust 的 `pub struct MultiProgress { state: Arc<RwLock<MultiState>> }`。
Rust 0.18.6 把 `state` 从 `pub(crate)` 改成了 `pub`(同时 `MultiState` 也 pub 了), 便于外部直接读写 multi 的状态(成员、orphan 行、对齐方式等)。Go 这边照做:字段导出。 注意 MultiState 自带 RWMutex,访问前要像 Rust 的 `read()/write()` 那样先加锁。
func DefaultMultiProgress ¶
func DefaultMultiProgress() *MultiProgress
func NewMultiProgress ¶
func NewMultiProgress() *MultiProgress
func WithDrawTarget ¶
func WithDrawTarget(dt ProgressDrawTarget) *MultiProgress
func (*MultiProgress) Add ¶
func (mp *MultiProgress) Add(pb *ProgressBar) *ProgressBar
func (*MultiProgress) Clear ¶
func (mp *MultiProgress) Clear() error
Clear 对应 Rust 的 MultiProgress::clear:返回底层 io 错误(之前恒返回 nil,错误被吞)。
func (*MultiProgress) Insert ¶
func (mp *MultiProgress) Insert(index uint, pb *ProgressBar) *ProgressBar
Insert / InsertFromBack 的 index 是 uint,对应 Rust 的 `insert(index: usize, ..)`。
func (*MultiProgress) InsertAfter ¶
func (mp *MultiProgress) InsertAfter(after *ProgressBar, pb *ProgressBar) *ProgressBar
func (*MultiProgress) InsertBefore ¶
func (mp *MultiProgress) InsertBefore(before *ProgressBar, pb *ProgressBar) *ProgressBar
func (*MultiProgress) InsertFromBack ¶
func (mp *MultiProgress) InsertFromBack(index uint, pb *ProgressBar) *ProgressBar
func (*MultiProgress) IsHidden ¶
func (mp *MultiProgress) IsHidden() bool
func (*MultiProgress) New ¶
func (mp *MultiProgress) New() *MultiProgress
func (*MultiProgress) Println ¶
func (mp *MultiProgress) Println(msg string) error
Println 对应 Rust 的 MultiProgress::println:返回底层 io 错误(之前恒返回 nil,错误被吞)。
func (*MultiProgress) Remove ¶
func (mp *MultiProgress) Remove(pb *ProgressBar)
Remove 对应 Rust 的 MultiProgress::remove:
- 只移除「确实插在本 MultiProgress 上」的进度条(Rust 是 `assert!(Arc::ptr_eq(..))`, Go 里没有 Arc,退化成比 Remote() 拿到的 MultiState 是否同一个);
- 先把这条 bar 的绘制目标置成 hidden,再回收槽位 —— 不置的话,旧 ProgressBar 仍指向 该槽位,槽位被后来的 bar 复用后它会画到别人的行上。
func (*MultiProgress) SetAlignment ¶
func (mp *MultiProgress) SetAlignment(alignment MultiProgressAlignment)
func (*MultiProgress) SetDrawTarget ¶
func (mp *MultiProgress) SetDrawTarget(target ProgressDrawTarget)
SetDrawTarget 对应 Rust 的 MultiProgress::set_draw_target:
state.draw_target.disconnect(Instant::now()); // 先断开旧的 state.draw_target = target; // 再换新的
Go 这边 MultiState 持有的是 multiDrawTarget 包装层,所以断开的是包装层里的旧目标, 换上去的也重新包一层(包装层负责聚合出帧,不能直接丢)。
func (*MultiProgress) SetMoveCursor ¶
func (mp *MultiProgress) SetMoveCursor(moveCursor bool)
func (*MultiProgress) Suspend ¶
func (mp *MultiProgress) Suspend(f func() interface{}) interface{}
func (*MultiProgress) WithDrawTarget ¶
func (mp *MultiProgress) WithDrawTarget(dt ProgressDrawTarget) *MultiProgress
type MultiProgressAlignment ¶
type MultiProgressAlignment int
const ( MultiProgressAlignmentTop MultiProgressAlignment = iota MultiProgressAlignmentBottom )
type MultiState ¶
type MultiState struct {
// contains filtered or unexported fields
}
--- MultiState and helpers ---
func NewMultiState ¶
func NewMultiState(dt ProgressDrawTarget) *MultiState
type MultiStateMember ¶
type MultiStateMember struct {
// contains filtered or unexported fields
}
MultiStateMember 对应 Rust 的 `struct MultiStateMember`:
draw_state: Option<DrawState> —— 成员上一次绘制留下的行 is_zombie: bool —— 对应的 ProgressBar(准确说是 BarState)是否已"死亡"
type MultiStateStub ¶
type MultiStateStub struct {
// contains filtered or unexported fields
}
MultiStateStub with reference to actual MultiState to expose Suspend
func (*MultiStateStub) Suspend ¶
func (m *MultiStateStub) Suspend(f func() interface{}, now time.Time) interface{}
type ProgressBar ¶
type ProgressBar struct {
// contains filtered or unexported fields
}
ProgressBar 是对 Rust `ProgressBar` 的 Go 移植,尽量保持 1:1 的逻辑。
设计说明: - 内部状态由 `BarState` 表示(在 state.go 中实现)。 - 使用原子变量记录位置,支持并发更新。 - 支持后台稳定 ticker(EnableSteadyTick/DisableSteadyTick)。 - 提供与 Rust 接口相似的方法名(小写导出以匹配包内部使用时可见性要求)。
func NewSpinner ¶
func NewSpinner() *ProgressBar
NewSpinner 创建一个 spinner 风格的进度条(对应 Rust 的 ProgressStyle::default_spinner())。
func NewWithDrawTarget ¶
func NewWithDrawTarget(length *uint64, dt ProgressDrawTarget) *ProgressBar
NewWithDrawTarget 使用指定长度和绘制目标创建进度条。
func (*ProgressBar) AbandonWithMessage ¶
func (p *ProgressBar) AbandonWithMessage(msg string)
AbandonWithMessage 标记完成但保留当前进度显示,并设置消息。
func (*ProgressBar) Clone ¶
func (p *ProgressBar) Clone() *ProgressBar
Clone 返回一个对相同内部状态与位置的浅拷贝,语义类似 Rust 的 Arc::clone。
func (*ProgressBar) DisableSteadyTick ¶
func (p *ProgressBar) DisableSteadyTick()
DisableSteadyTick 停止后台定时器。
func (*ProgressBar) Downgrade ¶
func (p *ProgressBar) Downgrade() WeakProgressBar
func (*ProgressBar) Duration ¶
func (p *ProgressBar) Duration() time.Duration
Duration 返回预计总时长(已用时间 + ETA)
func (*ProgressBar) EnableSteadyTick ¶
func (p *ProgressBar) EnableSteadyTick(interval time.Duration)
EnableSteadyTick 启动后台定时器以周期性 tick。
func (*ProgressBar) Finish ¶
func (p *ProgressBar) Finish()
Finish 标记完成并保留当前消息。 与 Rust 一致:不停 ticker,ticker 线程自己会在下一轮检测到 is_finished 后退出。
func (*ProgressBar) FinishUsingStyle ¶
func (p *ProgressBar) FinishUsingStyle()
FinishUsingStyle 使用当前存储的样式完成进度条(与 Rust 行为一致)。
func (*ProgressBar) FinishWithMessage ¶
func (p *ProgressBar) FinishWithMessage(msg string)
FinishWithMessage 完成并设置消息。
func (*ProgressBar) Inc ¶
func (p *ProgressBar) Inc(delta uint64)
Inc 增加位置。
对应 Rust:
self.pos.inc(delta);
let now = Instant::now();
if self.pos.allow(now) {
self.tick_inner(now); // ← now 是**同一个**时刻,不会重取
}
func (*ProgressBar) Index ¶
func (p *ProgressBar) Index() (uint, bool)
Index 返回在 MultiProgress 中的索引(如果存在)
对应 Rust 的 `ProgressBar::index()`:返回的是 `MultiState::members` 的**不透明下标** (槽位会被 free_set 复用,所以它与屏幕上的先后无关)。要看屏幕位置用 VisualIndex。
func (*ProgressBar) SetDrawTarget ¶
func (p *ProgressBar) SetDrawTarget(dt ProgressDrawTarget)
SetDrawTarget 切换绘制目标(会断开先前目标)。
func (*ProgressBar) SetElapsed ¶
func (p *ProgressBar) SetElapsed(elapsed time.Duration)
SetElapsed 设置已用时间(对应 Rust 的 set_elapsed:把起始时间往前推 elapsed)。
func (*ProgressBar) SetMessage ¶
func (p *ProgressBar) SetMessage(msg string)
SetMessage 设置消息(对应 Rust 的 set_message,设置后立即更新估算并重绘)。
func (*ProgressBar) SetPrefix ¶
func (p *ProgressBar) SetPrefix(prefix string)
SetPrefix 设置前缀(对应 Rust 的 set_prefix,设置后立即更新估算并重绘)。
func (*ProgressBar) SetTabWidth ¶
func (p *ProgressBar) SetTabWidth(w int)
SetTabWidth 设置制表符宽度(默认 8),与 Rust 一致:设置后强制重绘一次。
func (*ProgressBar) Suspend ¶
func (p *ProgressBar) Suspend(f func() interface{}) interface{}
Suspend 隐藏进度条,执行 f,再重绘,并返回 f 的结果。 对应 Rust 的 `suspend<F: FnOnce() -> R, R>(f) -> R`;Go 的方法不支持类型参数,故 R 退化为 any。
func (*ProgressBar) Update ¶
func (p *ProgressBar) Update(f func(*ProgressState))
Update 在内部 ProgressState 上执行 f,对应 Rust 的 `update(f: impl FnOnce(&mut ProgressState))`: 闭包拿到的是可变状态;随后仅当没有安装 steady ticker 时才 tick(Rust 的 `self.ticker.lock().unwrap().is_none()`)。
func (*ProgressBar) VisualIndex ¶
func (p *ProgressBar) VisualIndex() (uint, bool)
VisualIndex 返回在 MultiProgress 中的**屏幕位置**(第几行),不在任何 MultiProgress 里时返回 false。
对应 Rust 0.18.6 新增的 `ProgressBar::visual_index()`:
self.state().draw_target.remote().map(|(remote, idx)| remote.read().unwrap().visual_index(idx))
func (*ProgressBar) WithElapsed ¶
func (p *ProgressBar) WithElapsed(d time.Duration) *ProgressBar
WithElapsed 链式设置已用时间(简化实现)。
func (*ProgressBar) WithFinish ¶
func (p *ProgressBar) WithFinish(f ProgressFinish) *ProgressBar
WithFinish 链式设置完成行为。
func (*ProgressBar) WithMessage ¶
func (p *ProgressBar) WithMessage(msg string) *ProgressBar
WithMessage 链式设置消息。
func (*ProgressBar) WithPosition ¶
func (p *ProgressBar) WithPosition(pos uint64) *ProgressBar
WithPosition 链式设置位置。
func (*ProgressBar) WithPrefix ¶
func (p *ProgressBar) WithPrefix(prefix string) *ProgressBar
WithPrefix 链式设置前缀。
func (*ProgressBar) WithStyle ¶
func (p *ProgressBar) WithStyle(style ProgressStyle) *ProgressBar
WithStyle 链式设置样式并返回自身。
func (*ProgressBar) WithTabWidth ¶
func (p *ProgressBar) WithTabWidth(w int) *ProgressBar
WithTabWidth 链式设置制表符宽度(与 Rust 一致,链式设置不触发重绘)。
type ProgressBarIter ¶
type ProgressBarIter[T any] struct { // contains filtered or unexported fields }
ProgressBarIter 对应 Rust 的 ProgressBarIter<T>:包装一个迭代器(Go 里是切片), 每产出一个元素就把进度条往前推一格。
func NewProgressBarIterFromSlice ¶
func NewProgressBarIterFromSlice[T any](slice []T, pb *ProgressBar) *ProgressBarIter[T]
func Progress ¶
func Progress[T any](slice []T) *ProgressBarIter[T]
Progress 对应 `progress()`:用切片长度作为元素个数。
func ProgressCount ¶
func ProgressCount[T any](slice []T, count uint64) *ProgressBarIter[T]
ProgressCount 对应 `progress_count(len)`:显式给定元素个数。
func ProgressWithSlice ¶
func ProgressWithSlice[T any](slice []T, pb *ProgressBar) *ProgressBarIter[T]
ProgressWithSlice 对应 `progress_with(progress)`:用已有的进度条包装。
func ProgressWithStyle ¶
func ProgressWithStyle[T any](slice []T, style ProgressStyle) *ProgressBarIter[T]
ProgressWithStyle 对应 `progress_with_style(style)`。
func TryProgress ¶
func TryProgress[T any](slice []T) (*ProgressBarIter[T], bool)
TryProgress 对应 `try_progress()`:Rust 里只有 size_hint 的上界已知才返回 Some, Go 的切片长度恒已知,所以这里恒返回 true。
func WrapSlice ¶
func WrapSlice[T any](p *ProgressBar, slice []T) *ProgressBarIter[T]
WrapSlice 为切片创建一个 ProgressBarIter(Go 中的替代 wrap_iter)。
func (*ProgressBarIter[T]) Len ¶
func (p *ProgressBarIter[T]) Len() int
Len 对应 Rust 的 ExactSizeIterator::len:返回剩余元素个数。
func (*ProgressBarIter[T]) Next ¶
func (p *ProgressBarIter[T]) Next() (T, bool)
Next 对应 Rust 的 Iterator::next: 取到元素就 inc(1);取完了且进度条未结束,则 finish_using_style()(用样式里存的完成行为, 默认是 AndClear,不是 Finish() 的 AndLeave)。
func (*ProgressBarIter[T]) NextBack ¶
func (p *ProgressBarIter[T]) NextBack() (T, bool)
NextBack 对应 Rust 的 DoubleEndedIterator::next_back,推进逻辑与 next 相同。
func (*ProgressBarIter[T]) WithElapsed ¶
func (p *ProgressBarIter[T]) WithElapsed(elapsed time.Duration) *ProgressBarIter[T]
func (*ProgressBarIter[T]) WithFinish ¶
func (p *ProgressBarIter[T]) WithFinish(f ProgressFinish) *ProgressBarIter[T]
WithFinish 对应 Rust 的 with_finish(finish: ProgressFinish),整个 ProgressFinish(含 Msg)透传。
func (*ProgressBarIter[T]) WithMessage ¶
func (p *ProgressBarIter[T]) WithMessage(msg string) *ProgressBarIter[T]
func (*ProgressBarIter[T]) WithPosition ¶
func (p *ProgressBarIter[T]) WithPosition(pos uint64) *ProgressBarIter[T]
func (*ProgressBarIter[T]) WithPrefix ¶
func (p *ProgressBarIter[T]) WithPrefix(prefix string) *ProgressBarIter[T]
func (*ProgressBarIter[T]) WithStyle ¶
func (p *ProgressBarIter[T]) WithStyle(style ProgressStyle) *ProgressBarIter[T]
type ProgressDrawTarget ¶
type ProgressDrawTarget interface {
IsHidden() bool
IsStderr() bool
Drawable(force bool) Drawable
DrawableWithNow(force bool, now time.Time) Drawable
Width() *uint16
// 返回 (remoteState, idx, ok);idx 对应 Rust 的 `MultiStateIndex(usize)`
Remote() (*RemoteStub, uint, bool)
Disconnect(now time.Time)
AdjustLastLineCount(adjust LineAdjust)
// MarkZombie 对应 Rust 的 ProgressDrawTarget::mark_zombie:只有 Remote 变体(挂在
// MultiProgress 上的那条 bar)会真做事 —— 通知 MultiState 这条 bar 已"死亡"。
MarkZombie()
}
ProgressDrawTarget 接口:抽象出绘制目标的必要方法(逐步完善) ProgressDrawTarget 接口:抽象出绘制目标的必要方法(逐步完善)
Rust 侧的入口是 `drawable(force_draw, now)`,now 一路透传给速率限制器, 所以 Go 这边以 DrawableWithNow 为准,Drawable(force) 只是「取当前时刻」的便捷包装。
func NewHiddenDrawTarget ¶
func NewHiddenDrawTarget() ProgressDrawTarget
NewHiddenDrawTarget 对应 Rust 的 `hidden()`:完全不渲染。
func NewInMemoryDrawTarget ¶
func NewInMemoryDrawTarget(t *InMemoryTerm) ProgressDrawTarget
NewInMemoryDrawTarget 创建一个使用 InMemoryTerm 的 draw target(用于测试)。 对应 Rust 里 `ProgressDrawTarget::term_like(Box::new(InMemoryTerm::new(..)))` 的用法:不限速。
func NewRemoteDrawTarget ¶
func NewRemoteDrawTarget(ms *MultiState, idx uint) ProgressDrawTarget
func NewStderrDrawTarget ¶
func NewStderrDrawTarget() ProgressDrawTarget
NewStderrDrawTarget 对应 Rust 的 `stderr()`:buffered stderr,每秒最多 20 次。 这是进度条的默认绘制目标(New / NoLength / NewSpinner 都用它)。
func NewStderrDrawTargetWithHz ¶
func NewStderrDrawTargetWithHz(refreshRate uint8) ProgressDrawTarget
NewStderrDrawTargetWithHz 对应 Rust 的 `stderr_with_hz(refresh_rate)`。
func NewStdoutDrawTarget ¶
func NewStdoutDrawTarget() ProgressDrawTarget
NewStdoutDrawTarget 对应 Rust 的 `stdout()`:buffered stdout,每秒最多 20 次。
func NewStdoutDrawTargetWithHz ¶
func NewStdoutDrawTargetWithHz(refreshRate uint8) ProgressDrawTarget
NewStdoutDrawTargetWithHz 对应 Rust 的 `stdout_with_hz(refresh_rate)`。
func NewTermDrawTarget ¶
func NewTermDrawTarget(term TermLike, refreshRate uint8) ProgressDrawTarget
NewTermDrawTarget 对应 Rust 的 `term(term, refresh_rate)`。
func NewTermLikeDrawTarget ¶
func NewTermLikeDrawTarget(termLike TermLike) ProgressDrawTarget
NewTermLikeDrawTarget 对应 Rust 的 `term_like(term_like)`: 注意它没有默认刷新率(不限速),需要限速请用 NewTermLikeDrawTargetWithHz。
func NewTermLikeDrawTargetWithHz ¶
func NewTermLikeDrawTargetWithHz(termLike TermLike, refreshRate uint8) ProgressDrawTarget
NewTermLikeDrawTargetWithHz 对应 Rust 的 `term_like_with_hz(term_like, refresh_rate)`。
type ProgressFinish ¶
type ProgressFinish struct {
Kind FinishKind
Msg string
}
func DefaultProgressFinish ¶
func DefaultProgressFinish() ProgressFinish
type ProgressReaderIter ¶
type ProgressReaderIter struct {
// contains filtered or unexported fields
}
func NewProgressReaderIter ¶
func NewProgressReaderIter(r io.Reader, pb *ProgressBar) *ProgressReaderIter
type ProgressState ¶
type ProgressState struct {
// contains filtered or unexported fields
}
func NewProgressState ¶
func NewProgressState(len *uint64, pos *AtomicPosition) ProgressState
func (*ProgressState) Duration ¶
func (ps *ProgressState) Duration() time.Duration
Duration 返回预计总时长,对应 Rust 的 ProgressState::duration():
- 完成态(DoneVisible/DoneHidden):返回落库的时长;
- 进行中且已知长度:已用时间 + ETA(Rust 的 saturating_add);
- 进行中且未知长度:0。
func (*ProgressState) Elapsed ¶
func (ps *ProgressState) Elapsed() time.Duration
func (*ProgressState) Eta ¶
func (ps *ProgressState) Eta() time.Duration
func (*ProgressState) Fraction ¶
func (ps *ProgressState) Fraction() float32
func (*ProgressState) IsFinished ¶
func (ps *ProgressState) IsFinished() bool
func (*ProgressState) Len ¶
func (ps *ProgressState) Len() *uint64
func (*ProgressState) PerSec ¶
func (ps *ProgressState) PerSec() float64
PerSec 对应 Rust 的 per_sec:进行中用估算器的平滑速率; 已完成则用「总步数 / 总耗时」这个真实平均速率(Rust 明确分了两支)。
func (*ProgressState) Pos ¶
func (ps *ProgressState) Pos() uint64
func (*ProgressState) SetLen ¶
func (ps *ProgressState) SetLen(v uint64)
func (*ProgressState) SetPos ¶
func (ps *ProgressState) SetPos(v uint64)
type ProgressStyle ¶
type ProgressStyle struct {
// contains filtered or unexported fields
}
func DefaultProgressStyleBar ¶
func DefaultProgressStyleBar() ProgressStyle
func DefaultProgressStyleSpinner ¶
func DefaultProgressStyleSpinner() ProgressStyle
func NewProgressStyle ¶
func NewProgressStyle(tpl Template) ProgressStyle
NewProgressStyle constructs a ProgressStyle using the provided template and initializes other defaults (tick strings, progress chars, char width, tab width). This mirrors Rust's `Self::new(template)` constructor so callers doing `ProgressStyle::with_template(template)` will get the same initialization order.
func ProgressStyleWithTemplate ¶
func ProgressStyleWithTemplate(template string) (ProgressStyle, error)
ProgressStyleWithTemplate creates a ProgressStyle based on the default bar but replaces the template with the provided template string. This mirrors the Rust API `ProgressStyle::with_template("...")` used in tests.
func (*ProgressStyle) FormatState ¶
func (ps *ProgressStyle) FormatState(state *ProgressState, targetWidth int, forStderr bool) ([]LineType, []string)
FormatState 将 ProgressState 格式化为若干行及对应文本内容(返回 line types 与 contents)。 这是一个简化实现,支持常见占位符替换并返回渲染文本,便于 DrawStateStub.contents 填充。
func (ProgressStyle) ProgressChars ¶
func (ps ProgressStyle) ProgressChars(s string) ProgressStyle
Builder-style methods to mirror Rust's chaining API (consume-and-return Self) ProgressChars mirrors Rust's `progress_chars` and returns an updated copy.
func (*ProgressStyle) SetForStderr ¶
func (ps *ProgressStyle) SetForStderr()
SetForStderr updates placeholder-level styles to their stderr variants.
func (*ProgressStyle) SetProgressChars ¶
func (ps *ProgressStyle) SetProgressChars(s string)
SetProgressChars sets the progress characters sequence like "##-". Each rune becomes a cluster in progressChars; updates charWidth accordingly.
func (*ProgressStyle) SetTabWidth ¶
func (ps *ProgressStyle) SetTabWidth(w int)
func (ProgressStyle) Template ¶
func (ps ProgressStyle) Template(s string) (ProgressStyle, error)
Template mirrors Rust's `template(mut self, s: &str) -> Result<Self, TemplateError>` It parses the template and returns the updated ProgressStyle or an error.
func (ProgressStyle) TickChars ¶
func (ps ProgressStyle) TickChars(s string) ProgressStyle
TickChars mirrors Rust's `tick_chars` which accepts a string of grapheme clusters.
func (ProgressStyle) TickStrings ¶
func (ps ProgressStyle) TickStrings(ss []string) ProgressStyle
TickStrings mirrors Rust's `tick_strings` which accepts a slice of strings.
func (*ProgressStyle) WithKey ¶
func (ps *ProgressStyle) WithKey(key string, f func(*ProgressState) string)
WithKey registers a custom formatter for a template key.
func (*ProgressStyle) WithKeyStyle ¶
func (ps *ProgressStyle) WithKeyStyle(key string, f func(*ProgressState, bool) (string, *Style))
WithKeyStyle registers a custom formatter that may also return a *Style to apply to the rendered text. Formatter-provided styles take precedence over placeholder-level style/alt-style.
func (*ProgressStyle) WithTracker ¶
func (ps *ProgressStyle) WithTracker(key string, t ProgressTracker)
WithTracker registers a ProgressTracker directly (closest to Rust API).
type ProgressTracker ¶
type ProgressTracker interface {
Clone() ProgressTracker
Tick(state *ProgressState, now time.Time)
Reset(state *ProgressState, now time.Time)
Write(state *ProgressState, w *tabWriter)
}
ProgressTracker mirrors Rust's trait: it can be stateful, tick/reset, and write its representation into a writer.
type ProgressWriterIter ¶
type ProgressWriterIter struct {
// contains filtered or unexported fields
}
func NewProgressWriterIter ¶
func NewProgressWriterIter(w io.Writer, pb *ProgressBar) *ProgressWriterIter
func (*ProgressWriterIter) Flush ¶
func (pw *ProgressWriterIter) Flush() error
Flush 对应 Rust 的 io::Write::flush:直接透传给底层 writer。
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter mirrors the Rust implementation: interval in milliseconds, a capacity allowing occasional bursts, and a timestamp of the previous allowance calculation.
type RemoteStub ¶
type RemoteStub struct {
// contains filtered or unexported fields
}
RemoteStub references a MultiState for remote operations
func (*RemoteStub) StateWrite ¶
func (r *RemoteStub) StateWrite() *MultiStateStub
type SafeBarState ¶
type SafeBarState struct {
// contains filtered or unexported fields
}
SafeBarState 是对 BarState 的线程安全包装,模拟 Rust 中的 Arc<Mutex<BarState>> 行为。
func NewSafeBarState ¶
func NewSafeBarState(b *BarState) *SafeBarState
func (*SafeBarState) Draw ¶
func (s *SafeBarState) Draw(force bool) error
func (*SafeBarState) DrawWithNow ¶
func (s *SafeBarState) DrawWithNow(force bool, now time.Time) error
func (*SafeBarState) Duration ¶
func (s *SafeBarState) Duration() time.Duration
func (*SafeBarState) Elapsed ¶
func (s *SafeBarState) Elapsed() time.Duration
func (*SafeBarState) Eta ¶
func (s *SafeBarState) Eta() time.Duration
func (*SafeBarState) FinishUsingStyle ¶
func (s *SafeBarState) FinishUsingStyle(now time.Time, f ProgressFinish)
func (*SafeBarState) FormatForWidth ¶
func (s *SafeBarState) FormatForWidth(width int) ([]LineType, []string)
FormatForWidth returns the formatted lines and contents for the bar under the SafeBarState lock.
func (*SafeBarState) GetOnFinish ¶
func (s *SafeBarState) GetOnFinish() ProgressFinish
func (*SafeBarState) Index ¶
func (s *SafeBarState) Index() (uint, bool)
Index 对应 Rust 的 `ProgressBar::index() -> Option<MultiStateIndex>`(usize → uint)。
func (*SafeBarState) IsFinished ¶
func (s *SafeBarState) IsFinished() bool
Accessors for inner ProgressState values
func (*SafeBarState) IsHidden ¶
func (s *SafeBarState) IsHidden() bool
func (*SafeBarState) Len ¶
func (s *SafeBarState) Len() *uint64
func (*SafeBarState) Message ¶
func (s *SafeBarState) Message() string
func (*SafeBarState) PerSec ¶
func (s *SafeBarState) PerSec() float64
func (*SafeBarState) Pos ¶
func (s *SafeBarState) Pos() uint64
func (*SafeBarState) Position ¶
func (s *SafeBarState) Position() uint64
func (*SafeBarState) Prefix ¶
func (s *SafeBarState) Prefix() string
func (*SafeBarState) SetDrawTarget ¶
func (s *SafeBarState) SetDrawTarget(dt ProgressDrawTarget)
func (*SafeBarState) SetElapsed ¶
func (s *SafeBarState) SetElapsed(d time.Duration)
SetElapsed sets the progress start time so that elapsed time equals d.
func (*SafeBarState) SetMessage ¶
func (s *SafeBarState) SetMessage(msg string)
func (*SafeBarState) SetOnFinish ¶
func (s *SafeBarState) SetOnFinish(f ProgressFinish)
func (*SafeBarState) SetPos ¶
func (s *SafeBarState) SetPos(v uint64)
func (*SafeBarState) SetPrefix ¶
func (s *SafeBarState) SetPrefix(prefix string)
func (*SafeBarState) SetStyle ¶
func (s *SafeBarState) SetStyle(style ProgressStyle)
func (*SafeBarState) SetTabWidth ¶
func (s *SafeBarState) SetTabWidth(w int)
func (*SafeBarState) Style ¶
func (s *SafeBarState) Style() ProgressStyle
func (*SafeBarState) Suspend ¶
func (s *SafeBarState) Suspend(now time.Time, f func() interface{}) interface{}
func (*SafeBarState) TabWidth ¶
func (s *SafeBarState) TabWidth() int
func (*SafeBarState) Tick ¶
func (s *SafeBarState) Tick(now time.Time)
func (*SafeBarState) UnsetLength ¶
func (s *SafeBarState) UnsetLength(now time.Time)
func (*SafeBarState) Update ¶
func (s *SafeBarState) Update(now time.Time, f func(*ProgressState), tick bool)
func (*SafeBarState) VisualIndex ¶
func (s *SafeBarState) VisualIndex() (uint, bool)
VisualIndex 对应 Rust 的 `ProgressBar::visual_index()`: 取所属 MultiProgress 里的**屏幕位置**(ordering 中的下标)。
type SeekMax ¶
type SeekMax struct {
// contains filtered or unexported fields
}
SeekMax 记住最近 HISTORY 次位置里最大的那个,用来把抖动的 seek 摊平成单调的位置显示。 与 Rust 一致:缓冲只在发生过 seek 之后才启用(Rust 里是 Option), 连续 RESET 次顺序读写之后丢弃历史回到「直通」模式。
func NewSeekMax ¶
func NewSeekMax() *SeekMax
func (*SeekMax) UpdateSeek ¶
UpdateSeek 对应 Rust 的 update_seek:一旦 seek 过就启用缓冲并清掉顺序计数。
type Status ¶
type Status struct {
// contains filtered or unexported fields
}
func StatusDoneHidden ¶
func StatusDoneVisible ¶
func StatusInProgress ¶
func StatusInProgress() Status
type StatusKind ¶
type StatusKind int
Status 对应 Rust 的 `enum Status { InProgress, DoneVisible(Duration), DoneHidden(Duration) }`。 完成态必须携带落库时长(Rust 由 enum 的字段承载),ProgressState.Duration() 依赖它。
const ( StatusKindInProgress StatusKind = iota StatusKindDoneVisible StatusKindDoneHidden )
type StdTerm ¶
type StdTerm struct {
// contains filtered or unexported fields
}
StdTerm 是一个简单的终端实现,向指定的 io.Writer 写入,并通过 ANSI 控制序列移动光标。
func NewStdTerm ¶
func NewStdTerm() *StdTerm
NewStdTerm 使用 stdout 创建默认终端,对应 Rust 的 `Term::buffered_stdout()` (`ProgressDrawTarget::stdout()` 用的就是这个,带缓冲)。
func NewStdTermWithWriter ¶
NewStdTermWithWriter creates a StdTerm that writes to the provided writer.
注意:这个便捷构造**不带缓冲**(写什么立刻进 writer)。上游没有直接对应的构造, 带缓冲的那两个是 `buffered_stdout()` / `buffered_stderr()` —— 要走缓冲语义请用 NewStdTerm / NewStderrTerm。
func NewStderrTerm ¶
func NewStderrTerm() *StdTerm
NewStderrTerm 使用 stderr 创建终端,对应 Rust 的 `Term::buffered_stderr()`。 进度条的默认绘制目标是 stderr,所以 `ProgressDrawTarget::stderr()` 走的是这个。
func (*StdTerm) Flush ¶
Flush 对应 Rust 的 `Term::flush()`:
if let Some(ref buffer) = self.inner.buffer {
let mut buffer = buffer.lock().unwrap();
if !buffer.is_empty() {
self.write_through(&buffer[..])?; // 一次性落盘
buffer.clear();
}
}
一帧只 flush 一次(indicatif 在 draw_to_term 末尾调),所以终端每帧只重绘一次 —— 这就是"丝滑"与"闪"的分界:带缓冲时清屏与重画合成一次写,不带缓冲时终端会看到 中间的清屏状态。不带缓冲时退化成原来"底层 writer 有 Flush 就调"的行为。
func (*StdTerm) MoveCursorDown ¶
func (*StdTerm) MoveCursorLeft ¶
func (*StdTerm) MoveCursorRight ¶
func (*StdTerm) MoveCursorUp ¶
type Style ¶
Style represents a simple style descriptor (wraps the style spec string) that can be applied to text to produce ANSI-wrapped output.
type TabExpandedString ¶
type TabExpandedString struct {
// contains filtered or unexported fields
}
--- TabExpandedString ---
func NewTabExpandedString ¶
func NewTabExpandedString(s string, tabWidth int) TabExpandedString
func (*TabExpandedString) Expanded ¶
func (t *TabExpandedString) Expanded() string
func (*TabExpandedString) SetTabWidth ¶
func (t *TabExpandedString) SetTabWidth(w int)
type Template ¶
type Template struct {
Parts []TemplatePart
// contains filtered or unexported fields
}
func Template_from_str ¶
Template_from_str mirrors Rust's Template::from_str(s)
func Template_from_str_with_tab_width ¶
Template_from_str_with_tab_width 是 Rust 的 Template::from_str_with_tab_width 的直译: 同一个状态机、同一套分支,包括
- `{{` → 字面量 `{`、`}}` → 字面量 `}`(Rust 的 MaybeOpen/DoubleClose 两支)
- 键名位置遇到 ASCII 空白 → 回退成字面量 "{...}"(Rust 的 backtrack)
- `{key!}` / `{key:>10!}` 的截断位
- 无法匹配的状态+字符 → 返回 TemplateError(Rust 是 Err,Go 之前恒返回 nil)
func (*Template) SetTabWidth ¶
type TemplateError ¶
type TemplateError struct {
State templateState
Next rune
}
TemplateError 对应 Rust 的 `pub struct TemplateError { state, next }` (Rust 的 Display:`TemplateError: unexpected character {:?} in state {:?}`)。
func (*TemplateError) Error ¶
func (e *TemplateError) Error() string
type TemplatePart ¶
type TemplatePart struct {
IsPlaceholder bool
Text string
Key string
Align rune // '<' '^' '>' or 0
Width int // 0 means none
Truncate bool
Style *Style
AltStyle *Style
}
Template -----------------------------------------------------------------
type TermLike ¶
type TermLike interface {
Width() uint16
Height() uint16
MoveCursorUp(n int) error
MoveCursorDown(n int) error
MoveCursorRight(n int) error
MoveCursorLeft(n int) error
WriteLine(s string) error
WriteStr(s string) error
ClearLine() error
Flush() error
}
TermLike 表示最小的终端行为抽象(源自 src/term_like.rs),中文注释对应 Rust 注释。
type TickerHandle ¶
type TickerHandle struct {
// contains filtered or unexported fields
}
TickerHandle 是一个简单 ticker 控制句柄,供 EnableSteadyTick 使用。
func NewTickerHandle ¶
func NewTickerHandle(interval time.Duration, pb *ProgressBar) *TickerHandle
NewTickerHandle 启动后台 ticker,语义对应 Rust 的 `Ticker::new` + `TickerControl::run`: 循环体是「先判完成 → tick → 等一个 interval」,进度条一完成就自行退出,不需要调用方显式停。 另一条退出路径(进度条被回收)由 SafeBarState 上的 finalizer 兜住,等价于 Rust 的 `Weak::upgrade()` 失败。
func (*TickerHandle) Stop ¶
func (th *TickerHandle) Stop()
type VisualLines ¶
type VisualLines int
VisualLines represents a count of visual lines (wrap-aware).
func VisualLinesFromInt ¶
func VisualLinesFromInt(i int) VisualLines
func (VisualLines) AsInt ¶
func (v VisualLines) AsInt() int
func (VisualLines) SaturatingAdd ¶
func (v VisualLines) SaturatingAdd(o VisualLines) VisualLines
func (VisualLines) SaturatingSub ¶
func (v VisualLines) SaturatingSub(o VisualLines) VisualLines
type WeakProgressBar ¶
type WeakProgressBar struct {
// contains filtered or unexported fields
}
弱引用类型
func NewWeakProgressBar ¶
func NewWeakProgressBar() WeakProgressBar
func (WeakProgressBar) Upgrade ¶
func (w WeakProgressBar) Upgrade() *ProgressBar
type Width ¶
type Width struct{}
padAndTruncate returns a string that when measured occupies exactly width columns according to measureTextWidth. If truncate is true, content is truncated to fit. Width 对应 Rust 的 `pub struct Width`:宽度的计算入口,带一个全局的 「歧义宽度(CJK)」开关。
Rust 里宽度计算分散在 `measure_text_width` / `UnicodeWidthChar::width` 两处, 0.18.6 把它们收进了这个结构,并允许切换 CJK 口径:
WIDTH.char('█') // 默认 1,set_default_cjk(true) 后 2
WIDTH.str(s) // 纯文本宽度
WIDTH.ansi_str(s) // 跳过 ANSI 段后的可见宽度
func (Width) SetDefaultCJK ¶
SetDefaultCJK 对应 Rust 的 `Width::set_default_cjk(is_cjk)`。
打开后,"歧义宽度"字符(如 █、○、± 等 East Asian Ambiguous)按 2 列计算, 适合终端**真的**把方块字符渲染成双宽的 CJK 环境(Rust 侧是 `UnicodeWidthChar::width_cjk` / `UnicodeWidthStr::width_cjk`)。 只影响本包,不去改 go-runewidth 的全局 DefaultCondition。
