aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2017-04-12 01:27:34 +0200
committerDimitri Sokolyuk <demon@dim13.org>2017-04-12 01:27:34 +0200
commit910f7ee6dd0fff13237dc9ebde41d06c8395ed38 (patch)
treed2db8ae4adc17acf835b4207981cc39dc30910b6
parent33b10b165d747bb71ba8446e23ce5c5df195e07e (diff)
progress bar
-rw-r--r--main.go42
1 files 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) {
}
}