Debian Codegraph @

progressbar.go

raw
1 package desync
2
3 import (
4 "fmt"
5 "os"
6 "time"
7
8 "golang.org/x/term"
9 pb "gopkg.in/cheggaaa/pb.v1"
10 )
11
12 // NewProgressBar initializes a wrapper for a https://github.com/cheggaaa/pb
13 // progressbar that implements desync.ProgressBar
14 func NewProgressBar(prefix string) ProgressBar {
15 if !term.IsTerminal(int(os.Stderr.Fd())) &&
16 os.Getenv("DESYNC_PROGRESSBAR_ENABLED") == "" &&
17 os.Getenv("DESYNC_ENABLE_PARSABLE_PROGRESS") == "" {
18 return NullProgressBar{}
19 }
20 bar := pb.New(0).Prefix(prefix)
21 bar.ShowCounters = false
22 bar.Output = os.Stderr
23 if os.Getenv("DESYNC_ENABLE_PARSABLE_PROGRESS") != "" {
24 // This is likely going to a journal or redirected to a file, lower the
25 // refresh rate from the default 200ms to a more manageable 500ms.
26 bar.SetRefreshRate(time.Millisecond * 500)
27 bar.ShowBar = false
28 // Write every progress update in a separate line, instead of using
29 // the default carriage returns.
30 bar.Callback = func(s string) { fmt.Fprintln(os.Stderr, s) }
31 bar.Output = nil
32 }
33 return DefaultProgressBar{bar}
34 }
35
36 // DefaultProgressBar wraps https://github.com/cheggaaa/pb and implements desync.ProgressBar
37 type DefaultProgressBar struct {
38 *pb.ProgressBar
39 }
40
41 // SetTotal sets the upper bounds for the progress bar
42 func (p DefaultProgressBar) SetTotal(total int) {
43 p.ProgressBar.SetTotal(total)
44 }
45
46 // Start displaying the progress bar
47 func (p DefaultProgressBar) Start() {
48 p.ProgressBar.Start()
49 }
50
51 // Set the current value
52 func (p DefaultProgressBar) Set(current int) {
53 p.ProgressBar.Set(current)
54 }
55
56 // Write the current state of the progressbar
57 func (p DefaultProgressBar) Write(b []byte) (n int, err error) {
58 return p.ProgressBar.Write(b)
59 }