github.com/benchkram/bob@v0.0.0-20240314204020-b7a57f2f9be9/pkg/nix/build_progress.go (about)

     1  package nix
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  )
     7  
     8  // buildProgress tracks building of a Nix package and write to std.Out its progress
     9  // example output: `go_1_18: ....`
    10  type buildProgress struct {
    11  	// packageName is the name of the package being built ex. go_1_18
    12  	packageName string
    13  	// padding is the padding in spaces after pkg_name:
    14  	padding string
    15  	// start time of progress
    16  	start time.Time
    17  
    18  	// ticker used to write a `.` at a certain interval
    19  	ticker *time.Ticker
    20  	// done channel to signal end of progress tracking and exit from the started goroutine
    21  	done chan bool
    22  }
    23  
    24  // newBuildProgress creates a new progress track for a package
    25  func newBuildProgress(pkgName, padding string) *buildProgress {
    26  	var bp buildProgress
    27  	bp.packageName = pkgName
    28  	bp.padding = padding
    29  	bp.done = make(chan bool)
    30  	return &bp
    31  }
    32  
    33  // Start will start progress tracking and write to os.Stout a dot after every duration passes
    34  func (bp *buildProgress) Start(duration time.Duration) {
    35  	fmt.Printf("%s:%s", bp.packageName, bp.padding)
    36  
    37  	bp.ticker = time.NewTicker(duration)
    38  
    39  	bp.start = time.Now()
    40  	fmt.Print(".")
    41  
    42  	go func() {
    43  		for {
    44  			select {
    45  			case <-bp.done:
    46  				return
    47  			case <-bp.ticker.C:
    48  				fmt.Print(".")
    49  			}
    50  		}
    51  	}()
    52  }
    53  
    54  // Stop will stop the current progress output
    55  func (bp *buildProgress) Stop() {
    56  	bp.ticker.Stop()
    57  	bp.done <- true
    58  }
    59  
    60  // Duration gives the duration of progress tracking
    61  func (bp *buildProgress) Duration() time.Duration {
    62  	return time.Since(bp.start)
    63  }