simplify StopAndClear

This commit is contained in:
Michael Yang 2023-11-17 10:13:13 -08:00
parent 976068369b
commit 3cb07d2773

View file

@ -3,12 +3,8 @@ package progress
import ( import (
"fmt" "fmt"
"io" "io"
"os"
"strings"
"sync" "sync"
"time" "time"
"golang.org/x/term"
) )
type State interface { type State interface {
@ -48,19 +44,18 @@ func (p *Progress) Stop() bool {
} }
func (p *Progress) StopAndClear() bool { func (p *Progress) StopAndClear() bool {
fmt.Fprint(p.w, "\033[?25l")
defer fmt.Fprint(p.w, "\033[?25h")
stopped := p.Stop() stopped := p.Stop()
if stopped { if stopped {
termWidth, _, err := term.GetSize(int(os.Stderr.Fd()))
if err != nil {
panic(err)
}
// clear the progress bar by: // clear the progress bar by:
// 1. reset to beginning of line // 1. for each line in the progress:
// 2. move up to the first line of the progress bar // a. move the cursor up one line
// 3. fill the terminal width with spaces // b. clear the line
// 4. reset to beginning of line for i := 0; i < p.pos; i++ {
fmt.Fprintf(p.w, "\r\033[%dA%s\r", p.pos, strings.Repeat(" ", termWidth)) fmt.Fprint(p.w, "\033[A\033[2K")
}
} }
return stopped return stopped
@ -77,6 +72,9 @@ func (p *Progress) render() error {
p.mu.Lock() p.mu.Lock()
defer p.mu.Unlock() defer p.mu.Unlock()
fmt.Fprint(p.w, "\033[?25l")
defer fmt.Fprint(p.w, "\033[?25h")
if p.pos > 0 { if p.pos > 0 {
fmt.Fprintf(p.w, "\033[%dA", p.pos) fmt.Fprintf(p.w, "\033[%dA", p.pos)
} }