|
| 1 | +// in is a commandline utility that sleeps for a specified amount of time |
| 2 | +// while displaying a progress bar. |
| 3 | +// |
| 4 | +// Ex: in 2m30s && run_a_command |
| 5 | +// |
| 6 | +// Author: Andrew Kallmeyer |
| 7 | +// Copyright 2021 Google LLC. |
| 8 | +// SPDX-License-Identifier: Apache-2.0 |
| 9 | +package main |
| 10 | + |
| 11 | +import ( |
| 12 | + "os" |
| 13 | + "fmt" |
| 14 | + "time" |
| 15 | + "strings" |
| 16 | +) |
| 17 | + |
| 18 | +const ( |
| 19 | + BarLen = 40 |
| 20 | + BarFilled = '=' |
| 21 | + BarEmpty = '-' |
| 22 | + Step = time.Second |
| 23 | +) |
| 24 | + |
| 25 | +const ClearLine = "\033[K" // ESC[K, the ECMA-48 CSI code for Erase line. See man 4 console_codes |
| 26 | + |
| 27 | +func progressbar(elapsed, total int64) string { |
| 28 | + const realBarLen = BarLen-2 // to account for the [ and ] |
| 29 | + |
| 30 | + // Solve for progress: total / BarLen = elapsed / progress |
| 31 | + progress := int(elapsed / (total / realBarLen)) |
| 32 | + if progress < 0 || progress > realBarLen { |
| 33 | + fmt.Fprintln(os.Stderr, "Bad miscaculation:", progress, elapsed, total, realBarLen) |
| 34 | + os.Exit(2) |
| 35 | + } |
| 36 | + |
| 37 | + var b strings.Builder |
| 38 | + b.WriteRune('[') |
| 39 | + for i := 0; i < progress; i+=1 { |
| 40 | + b.WriteRune(BarFilled) |
| 41 | + } |
| 42 | + for i := 0; i < (realBarLen - progress); i+=1 { |
| 43 | + b.WriteRune(BarEmpty) |
| 44 | + } |
| 45 | + b.WriteRune(']') |
| 46 | + return b.String() |
| 47 | +} |
| 48 | + |
| 49 | +func main() { |
| 50 | + if len(os.Args) < 2 { |
| 51 | + fmt.Fprintf(os.Stderr, "Usage example: %v 2m30s\n", os.Args[0]) |
| 52 | + os.Exit(127) |
| 53 | + } |
| 54 | + sleeptime, err := time.ParseDuration(os.Args[1]) |
| 55 | + if err != nil { |
| 56 | + fmt.Fprintln(os.Stderr, "Invalid duration:", os.Args[1]) |
| 57 | + os.Exit(1) |
| 58 | + } |
| 59 | + for elapsed := 0*time.Second; elapsed < sleeptime; elapsed += Step { |
| 60 | + fmt.Fprintf(os.Stderr, "\r%s %v/%v%s", |
| 61 | + progressbar(elapsed.Milliseconds(), sleeptime.Milliseconds()), |
| 62 | + elapsed, sleeptime, ClearLine) |
| 63 | + time.Sleep(Step) |
| 64 | + } |
| 65 | + fmt.Fprintf(os.Stderr, "\rDing!%s\n", ClearLine) |
| 66 | +} |
0 commit comments