github.com/michael-k/docker@v1.7.0-rc2/pkg/progressreader/progressreader.go (about)

     1  package progressreader
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/docker/docker/pkg/jsonmessage"
     7  	"github.com/docker/docker/pkg/streamformatter"
     8  )
     9  
    10  // Reader with progress bar
    11  type Config struct {
    12  	In         io.ReadCloser // Stream to read from
    13  	Out        io.Writer     // Where to send progress bar to
    14  	Formatter  *streamformatter.StreamFormatter
    15  	Size       int
    16  	Current    int
    17  	LastUpdate int
    18  	NewLines   bool
    19  	ID         string
    20  	Action     string
    21  }
    22  
    23  func New(newReader Config) *Config {
    24  	return &newReader
    25  }
    26  func (config *Config) Read(p []byte) (n int, err error) {
    27  	read, err := config.In.Read(p)
    28  	config.Current += read
    29  	updateEvery := 1024 * 512 //512kB
    30  	if config.Size > 0 {
    31  		// Update progress for every 1% read if 1% < 512kB
    32  		if increment := int(0.01 * float64(config.Size)); increment < updateEvery {
    33  			updateEvery = increment
    34  		}
    35  	}
    36  	if config.Current-config.LastUpdate > updateEvery || err != nil {
    37  		config.Out.Write(config.Formatter.FormatProgress(config.ID, config.Action, &jsonmessage.JSONProgress{Current: config.Current, Total: config.Size}))
    38  		config.LastUpdate = config.Current
    39  	}
    40  	// Send newline when complete
    41  	if config.NewLines && err != nil && read == 0 {
    42  		config.Out.Write(config.Formatter.FormatStatus("", ""))
    43  	}
    44  	return read, err
    45  }
    46  func (config *Config) Close() error {
    47  	config.Current = config.Size
    48  	config.Out.Write(config.Formatter.FormatProgress(config.ID, config.Action, &jsonmessage.JSONProgress{Current: config.Current, Total: config.Size}))
    49  	return config.In.Close()
    50  }