Skip to content

Commit

Permalink
add option to support ANSI escape code compatible environments
Browse files Browse the repository at this point in the history
  • Loading branch information
kirides committed Oct 26, 2020
1 parent 953dc78 commit b404f80
Showing 1 changed file with 33 additions and 5 deletions.
38 changes: 33 additions & 5 deletions progressbar.go
Expand Up @@ -93,6 +93,9 @@ type config struct {
invisible bool

onCompletion func()

// whether the render function should make use of ANSI codes to reduce console I/O
useANSICodes bool
}

// Theme defines the elements of the bar
Expand Down Expand Up @@ -229,6 +232,15 @@ func OptionShowBytes(val bool) Option {
}
}

// OptionUseANSICodes will use more optimized terminal i/o.
//
// Only useful in environments with support for ANSI escape sequences.
func OptionUseANSICodes(val bool) Option {
return func(p *ProgressBar) {
p.config.useANSICodes = val
}
}

var defaultTheme = Theme{Saucer: "█", SaucerPadding: " ", BarStart: "|", BarEnd: "|"}

// NewOptions constructs a new instance of ProgressBar, with any options you specify
Expand Down Expand Up @@ -496,10 +508,12 @@ func (p *ProgressBar) render() error {
return nil
}

// first, clear the existing progress bar
err := clearProgressBar(p.config, p.state)
if err != nil {
return err
if !p.config.useANSICodes {
// first, clear the existing progress bar
err := clearProgressBar(p.config, p.state)
if err != nil {
return err
}
}

// check if the progress bar is finished
Expand All @@ -514,6 +528,13 @@ func (p *ProgressBar) render() error {
}
}
if p.state.finished {
// when using ANSI codes we don't pre-clean the current line
if p.config.useANSICodes {
err := clearProgressBar(p.config, p.state)
if err != nil {
return err
}
}
return nil
}

Expand Down Expand Up @@ -724,11 +745,18 @@ func renderProgressBar(c config, s state) (int, error) {
// character count of the string, as some runes span multiple characters.
// see https://stackoverflow.com/a/12668840/2733724
stringWidth := runewidth.StringWidth(cleanString)

if c.useANSICodes {
// append the "clear rest of line" ANSI escape sequence
str = str + "\033[0K"
}
return stringWidth, writeString(c, str)
}

func clearProgressBar(c config, s state) error {
if c.useANSICodes {
// write the "clear current line" ANSI escape sequence
return writeString(c, "\033[2K\r")
}
// fill the current line with enough spaces
// to overwrite the progress bar and jump
// back to the beginning of the line
Expand Down

0 comments on commit b404f80

Please sign in to comment.