| 1 | |
| 2 | |
| 3 | |
| 4 | package progressbar |
| 5 | |
| 6 | import ( |
| 7 | "os" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/cheggaaa/pb/v3" |
| 11 | "github.com/mattn/go-isatty" |
| 12 | "github.com/sirupsen/logrus" |
| 13 | ) |
| 14 | |
| 15 | |
| 16 | type ProgressBar struct { |
| 17 | *pb.ProgressBar |
| 18 | } |
| 19 | |
| 20 | func (b *ProgressBar) Update(n int64) { |
| 21 | b.Add64(n) |
| 22 | } |
| 23 | |
| 24 | func New(size int64) (*ProgressBar, error) { |
| 25 | bar := &ProgressBar{pb.New64(size)} |
| 26 | |
| 27 | bar.Set(pb.Bytes, true) |
| 28 | |
| 29 | if showProgress() { |
| 30 | bar.SetTemplateString(`{{counters . }} {{bar . | green }} {{percent .}} {{speed . "%s/s"}}`) |
| 31 | bar.SetRefreshRate(200 * time.Millisecond) |
| 32 | } else { |
| 33 | bar.Set(pb.Static, true) |
| 34 | } |
| 35 | |
| 36 | bar.SetWidth(80) |
| 37 | if err := bar.Err(); err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | |
| 41 | return bar, nil |
| 42 | } |
| 43 | |
| 44 | func showProgress() bool { |
| 45 | |
| 46 | if _, ok := logrus.StandardLogger().Formatter.(*logrus.TextFormatter); !ok { |
| 47 | return false |
| 48 | } |
| 49 | |
| 50 | |
| 51 | logFd := os.Stderr.Fd() |
| 52 | return isatty.IsTerminal(logFd) || isatty.IsCygwinTerminal(logFd) |
| 53 | } |