ollama/progress/progress.go

95 lines
1.4 KiB
Go
Raw Normal View History

2023-11-14 19:33:16 -05:00
package progress
import (
"fmt"
"io"
2023-11-14 19:58:51 -05:00
"os"
"strings"
2023-11-14 19:33:16 -05:00
"sync"
"time"
2023-11-14 19:58:51 -05:00
"golang.org/x/term"
2023-11-14 19:33:16 -05:00
)
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 17:04:57 -05:00
p := &Progress{w: w}
2023-11-14 19:33:16 -05:00
go p.start()
return p
}
2023-11-14 19:58:51 -05:00
func (p *Progress) Stop() bool {
2023-11-14 19:33:16 -05:00
if p.ticker != nil {
p.ticker.Stop()
p.ticker = nil
p.render()
2023-11-14 19:58:51 -05:00
return true
2023-11-14 19:33:16 -05:00
}
2023-11-14 19:58:51 -05:00
return false
}
func (p *Progress) StopAndClear() bool {
stopped := p.Stop()
if stopped {
termWidth, _, err := term.GetSize(int(os.Stderr.Fd()))
if err != nil {
panic(err)
}
// clear the progress bar by:
// 1. reset to beginning of line
// 2. move up to the first line of the progress bar
// 3. fill the terminal width with spaces
// 4. reset to beginning of line
fmt.Fprintf(p.w, "\r\033[%dA%s\r", p.pos, strings.Repeat(" ", termWidth))
}
return stopped
2023-11-14 19:33:16 -05: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-15 17:04:57 -05:00
if p.pos > 0 {
fmt.Fprintf(p.w, "\033[%dA", p.pos)
}
2023-11-14 19:33:16 -05: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()
}
}