ollama/progress/progress.go

112 lines
1.6 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
w io.Writer
2023-11-15 00:33:16 +00:00
pos int
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
}
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) Stop() bool {
stopped := p.stop()
if stopped {
fmt.Fprint(p.w, "\n")
}
return stopped
}
2023-11-15 00:58:51 +00:00
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")
stopped := p.stop()
2023-11-15 00:58:51 +00:00
if stopped {
2023-11-19 18:46:19 +00:00
// clear all progress lines
2023-11-17 18:13:13 +00:00
for i := 0; i < p.pos; i++ {
if i > 0 {
fmt.Fprint(p.w, "\033[A")
}
fmt.Fprint(p.w, "\033[2K\033[1G")
2023-11-17 18:13:13 +00:00
}
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)
}
2023-12-15 22:07:34 +00:00
func (p *Progress) render() {
2023-11-15 00:33:16 +00:00
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")
// clear already rendered progress lines
for i := 0; i < p.pos; i++ {
if i > 0 {
fmt.Fprint(p.w, "\033[A")
}
fmt.Fprint(p.w, "\033[2K\033[1G")
2023-11-15 22:04:57 +00:00
}
// render progress lines
for i, state := range p.states {
fmt.Fprint(p.w, state.String())
if i < len(p.states)-1 {
fmt.Fprint(p.w, "\n")
}
2023-11-15 00:33:16 +00:00
}
p.pos = len(p.states)
2023-11-15 00:33:16 +00:00
}
func (p *Progress) start() {
p.ticker = time.NewTicker(100 * time.Millisecond)
for range p.ticker.C {
p.render()
}
}