Skip to content

Commit

Permalink
refactored to simplify code
Browse files Browse the repository at this point in the history
  • Loading branch information
schollz committed Apr 22, 2018
1 parent 5fb8484 commit 5441d79
Showing 1 changed file with 22 additions and 46 deletions.
68 changes: 22 additions & 46 deletions progressbar.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ type ProgressBar struct {

func (p *ProgressBar) SetTheme(theme []string) {
p.Lock()
defer p.Unlock()
p.theme = theme
p.Unlock()
}

// New returns a new ProgressBar
Expand Down Expand Up @@ -81,64 +81,40 @@ func (p *ProgressBar) SetWriter(w io.Writer) {

// Add with increase the current count on the progress bar
func (p *ProgressBar) Add(num int) error {
p.RLock()
currentNum := p.currentNum
p.RUnlock()
return p.Set(currentNum + num)
}

// Set will change the current count on the progress bar
func (p *ProgressBar) Set(num int) error {
p.Lock()
defer p.Unlock()
if p.max == 0 {
p.Unlock()
return errors.New("max must be greater than 0")
}
p.currentNum = num
p.currentNum += num
percent := float64(p.currentNum) / float64(p.max)
p.currentSaucerSize = int(percent * float64(p.size))
p.currentPercent = int(percent * 100)
updateBar := p.currentPercent != p.lastPercent && p.currentPercent > 0
p.lastPercent = p.currentPercent
p.Unlock()
if updateBar {
return p.Show()
}
return nil
}

// Show will print the current progress bar
func (p *ProgressBar) Show() error {
p.RLock()
defer p.RUnlock()
if p.currentNum > p.max {
return errors.New("current number exceeds max")
}

s := p.String()

_, err := io.WriteString(p.w, s)
if err != nil {
return err
}

if f, ok := p.w.(*os.File); ok {
f.Sync()
if updateBar {
leftTime := time.Since(p.startTime).Seconds() / float64(p.currentNum) * (float64(p.max) - float64(p.currentNum))
s := fmt.Sprintf("\r%4d%% %s%s%s%s [%s:%s] ",
p.currentPercent,
p.theme[2],
strings.Repeat(p.theme[0], p.currentSaucerSize),
strings.Repeat(p.theme[1], p.size-p.currentSaucerSize),
p.theme[3],
(time.Duration(time.Since(p.startTime).Seconds()) * time.Second).String(),
(time.Duration(leftTime) * time.Second).String(),
)
_, err := io.WriteString(p.w, s)
if err != nil {
return err
}

if f, ok := p.w.(*os.File); ok {
f.Sync()
}
}
return nil
}

func (p *ProgressBar) String() string {
p.RLock()
defer p.RUnlock()
leftTime := time.Since(p.startTime).Seconds() / float64(p.currentNum) * (float64(p.max) - float64(p.currentNum))
return fmt.Sprintf("\r%4d%% %s%s%s%s [%s:%s] ",
p.currentPercent,
p.theme[2],
strings.Repeat(p.theme[0], p.currentSaucerSize),
strings.Repeat(p.theme[1], p.size-p.currentSaucerSize),
p.theme[3],
(time.Duration(time.Since(p.startTime).Seconds()) * time.Second).String(),
(time.Duration(leftTime) * time.Second).String(),
)
}

0 comments on commit 5441d79

Please sign in to comment.