ollama/progress/progress.go

99 lines
1.5 KiB
Go
Raw Normal View History

2023-11-15 00:33:16 +00:00
package progress
import (
"fmt"
"io"
"sync"
"time"
)
type State interface {
String() string
}
type Progress struct {
mu sync.Mutex
pos int
w io.Writer
ticker *time.Ticker
states []State
}
func NewProgress(w io.Writer) *Progress {
2023-11-15 22:04:57 +00:00
p := &Progress{w: w}
2023-11-15 00:33:16 +00:00
go p.start()
return p
}
2023-11-15 00:58:51 +00:00
func (p *Progress) Stop() bool {
2023-11-16 00:59:49 +00:00
for _, state := range p.states {
if spinner, ok := state.(*Spinner); ok {
spinner.Stop()
}
}
2023-11-15 00:33:16 +00:00
if p.ticker != nil {
p.ticker.Stop()
p.ticker = nil
p.render()
2023-11-15 00:58:51 +00:00
return true
2023-11-15 00:33:16 +00:00
}
2023-11-15 00:58:51 +00:00
return false
}
func (p *Progress) StopAndClear() bool {
2023-11-17 18:13:13 +00:00
fmt.Fprint(p.w, "\033[?25l")
defer fmt.Fprint(p.w, "\033[?25h")
2023-11-15 00:58:51 +00:00
stopped := p.Stop()
if stopped {
// clear the progress bar by:
2023-11-17 18:13:13 +00:00
// 1. for each line in the progress:
// a. move the cursor up one line
// b. clear the line
for i := 0; i < p.pos; i++ {
fmt.Fprint(p.w, "\033[A\033[2K")
}
2023-11-15 00:58:51 +00:00
}
return stopped
2023-11-15 00:33:16 +00:00
}
func (p *Progress) Add(key string, state State) {
p.mu.Lock()
defer p.mu.Unlock()
p.states = append(p.states, state)
}
func (p *Progress) render() error {
p.mu.Lock()
defer p.mu.Unlock()
2023-11-17 18:13:13 +00:00
fmt.Fprint(p.w, "\033[?25l")
defer fmt.Fprint(p.w, "\033[?25h")
2023-11-15 22:04:57 +00:00
if p.pos > 0 {
fmt.Fprintf(p.w, "\033[%dA", p.pos)
}
2023-11-15 00:33:16 +00:00
for _, state := range p.states {
fmt.Fprintln(p.w, state.String())
}
if len(p.states) > 0 {
p.pos = len(p.states)
}
return nil
}
func (p *Progress) start() {
p.ticker = time.NewTicker(100 * time.Millisecond)
for range p.ticker.C {
p.render()
}
}