address code review comments

This commit is contained in:
Jeremy Schlatter 2025-02-18 14:50:09 -08:00
parent f9c7ead160
commit 78f403ff45
No known key found for this signature in database
GPG Key ID: 4D081B793DF81368

View File

@ -1,7 +1,7 @@
package progress package progress
import ( import (
"bytes" "bufio"
"fmt" "fmt"
"io" "io"
"sync" "sync"
@ -14,8 +14,8 @@ type State interface {
type Progress struct { type Progress struct {
mu sync.Mutex mu sync.Mutex
w io.Writer // buffer output to minimize flickering on all terminals
buf bytes.Buffer w *bufio.Writer
pos int pos int
@ -24,7 +24,7 @@ type Progress struct {
} }
func NewProgress(w io.Writer) *Progress { func NewProgress(w io.Writer) *Progress {
p := &Progress{w: w} p := &Progress{w: bufio.NewWriter(w)}
go p.start() go p.start()
return p return p
} }
@ -50,11 +50,14 @@ func (p *Progress) Stop() bool {
stopped := p.stop() stopped := p.stop()
if stopped { if stopped {
fmt.Fprint(p.w, "\n") fmt.Fprint(p.w, "\n")
p.w.Flush()
} }
return stopped return stopped
} }
func (p *Progress) StopAndClear() bool { func (p *Progress) StopAndClear() bool {
defer p.w.Flush()
fmt.Fprint(p.w, "\033[?25l") fmt.Fprint(p.w, "\033[?25l")
defer fmt.Fprint(p.w, "\033[?25h") defer fmt.Fprint(p.w, "\033[?25h")
@ -83,29 +86,26 @@ func (p *Progress) render() {
p.mu.Lock() p.mu.Lock()
defer p.mu.Unlock() defer p.mu.Unlock()
// buffer output to minimize flickering on all terminals defer p.w.Flush()
p.buf.Reset()
defer p.buf.WriteTo(p.w)
// eliminate flickering on terminals that support synchronized output // eliminate flickering on terminals that support synchronized output
fmt.Fprint(&p.buf, "\033[?2026h") fmt.Fprint(p.w, "\033[?2026h")
defer fmt.Fprint(&p.buf, "\033[?2026l") defer fmt.Fprint(p.w, "\033[?2026l")
fmt.Fprint(&p.buf, "\033[?25l") fmt.Fprint(p.w, "\033[?25l")
defer fmt.Fprint(&p.buf, "\033[?25h") defer fmt.Fprint(p.w, "\033[?25h")
// move the cursor back to the beginning // move the cursor back to the beginning
for range p.pos - 1 { for range p.pos - 1 {
fmt.Fprint(&p.buf, "\033[A") fmt.Fprint(p.w, "\033[A")
} }
fmt.Fprint(&p.buf, "\033[1G") fmt.Fprint(p.w, "\033[1G")
// render progress lines // render progress lines
for i, state := range p.states { for i, state := range p.states {
fmt.Fprint(&p.buf, state.String()) fmt.Fprint(p.w, state.String(), "\033[K")
fmt.Fprintf(&p.buf, "\033[K")
if i < len(p.states)-1 { if i < len(p.states)-1 {
fmt.Fprint(&p.buf, "\n") fmt.Fprint(p.w, "\n")
} }
} }