github.com/chenbh/concourse/v6@v6.4.2/fly/ui/progress/progress.go (about)

     1  package progress
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/chenbh/concourse/v6/fly/ui"
     7  	"github.com/vbauerster/mpb/v4"
     8  	"github.com/vbauerster/mpb/v4/decor"
     9  	"golang.org/x/sync/errgroup"
    10  )
    11  
    12  type Progress struct {
    13  	progress *mpb.Progress
    14  	errs     *errgroup.Group
    15  }
    16  
    17  func New() *Progress {
    18  	return &Progress{
    19  		progress: mpb.New(mpb.WithWidth(1)),
    20  		errs:     new(errgroup.Group),
    21  	}
    22  }
    23  
    24  func (prog *Progress) Go(name string, f func(*mpb.Bar) error) {
    25  	bar := prog.progress.AddSpinner(
    26  		0,
    27  		mpb.SpinnerOnLeft,
    28  		mpb.PrependDecorators(
    29  			decor.Name(
    30  				name,
    31  				decor.WC{W: len(name), C: decor.DSyncWidthR},
    32  			),
    33  		),
    34  		mpb.AppendDecorators(
    35  			decor.OnComplete(
    36  				decor.AverageSpeed(decor.UnitKiB, "(%.1f)"),
    37  				" "+ui.Embolden("done"),
    38  			),
    39  		),
    40  		mpb.BarClearOnComplete(),
    41  	)
    42  
    43  	prog.errs.Go(func() error {
    44  		err := f(bar)
    45  		if err != nil {
    46  			bar.Abort(false)
    47  			return fmt.Errorf("'%s' failed: %s", name, err)
    48  		}
    49  
    50  		bar.SetTotal(bar.Current(), true)
    51  
    52  		return nil
    53  	})
    54  }
    55  
    56  func (prog *Progress) Wait() error {
    57  	prog.progress.Wait()
    58  	return prog.errs.Wait()
    59  }