From 910f7ee6dd0fff13237dc9ebde41d06c8395ed38 Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Wed, 12 Apr 2017 01:27:34 +0200 Subject: progress bar --- main.go | 42 +++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/main.go b/main.go index 31d2043..de27ce1 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "os/signal" + "strings" "time" ) @@ -25,24 +26,44 @@ func display(ctx context.Context, s string) { if !ok { return } + total := time.Until(dl) ticker := time.NewTicker(time.Second) defer ticker.Stop() - defer fmt.Printf("\r%s done\x1b[K\n", s) + defer fmt.Println("") for range ticker.C { + fmt.Printf("\r%-20s %s", s, progress(total, time.Until(dl))) select { case <-ctx.Done(): return default: - left := time.Until(dl) - left -= left % time.Second - if left < 0 { - left = 0 - } - fmt.Printf("\r%s %s left\x1b[K", s, left) } } } +func total(t time.Time) { + fmt.Printf("total %v\n", round(time.Since(t))) +} + +func round(d time.Duration) time.Duration { + return d - d%time.Second +} + +func progress(total, left time.Duration) string { + width := 40 + if left < 0 { + left = 0 + } + todo := width * int(left) / int(total) + s := fmt.Sprintf("%3d%% |", 100-100*int(left)/int(total)) + s += strings.Repeat("*", width-todo) + strings.Repeat(" ", todo) + if left > 0 { + s += fmt.Sprintf("| %9s", round(left)) + } else { + s += fmt.Sprintf("| %9s", "done") + } + return s +} + func (o *Opt) doWork(ctx context.Context) stateFn { select { case <-ctx.Done(): @@ -100,12 +121,7 @@ func main() { cancel() }() - defer func(t time.Time) { - total := time.Since(t) - total -= total % time.Second - fmt.Printf("total %v\n", total) - }(time.Now()) - + defer total(time.Now()) for s := o.doWork; s != nil; s = s(ctx) { } } -- cgit v1.2.3