2015-02-24 03:51:46 -05:00
|
|
|
package progressreader
|
|
|
|
|
|
|
|
import (
|
2015-03-31 16:17:25 -04:00
|
|
|
"io"
|
|
|
|
|
2015-03-17 22:18:41 -04:00
|
|
|
"github.com/docker/docker/pkg/jsonmessage"
|
|
|
|
"github.com/docker/docker/pkg/streamformatter"
|
2015-02-24 03:51:46 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// Reader with progress bar
|
|
|
|
type Config struct {
|
|
|
|
In io.ReadCloser // Stream to read from
|
|
|
|
Out io.Writer // Where to send progress bar to
|
2015-03-17 22:18:41 -04:00
|
|
|
Formatter *streamformatter.StreamFormatter
|
2015-02-24 03:51:46 -05:00
|
|
|
Size int
|
|
|
|
Current int
|
|
|
|
LastUpdate int
|
|
|
|
NewLines bool
|
|
|
|
ID string
|
|
|
|
Action string
|
|
|
|
}
|
|
|
|
|
|
|
|
func New(newReader Config) *Config {
|
|
|
|
return &newReader
|
|
|
|
}
|
2015-05-27 11:48:51 -04:00
|
|
|
|
2015-02-24 03:51:46 -05:00
|
|
|
func (config *Config) Read(p []byte) (n int, err error) {
|
|
|
|
read, err := config.In.Read(p)
|
|
|
|
config.Current += read
|
|
|
|
updateEvery := 1024 * 512 //512kB
|
|
|
|
if config.Size > 0 {
|
|
|
|
// Update progress for every 1% read if 1% < 512kB
|
|
|
|
if increment := int(0.01 * float64(config.Size)); increment < updateEvery {
|
|
|
|
updateEvery = increment
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if config.Current-config.LastUpdate > updateEvery || err != nil {
|
2015-05-27 11:48:51 -04:00
|
|
|
updateProgress(config)
|
2015-02-24 03:51:46 -05:00
|
|
|
config.LastUpdate = config.Current
|
|
|
|
}
|
2015-05-27 11:48:51 -04:00
|
|
|
|
|
|
|
if err != nil && read == 0 {
|
|
|
|
updateProgress(config)
|
|
|
|
if config.NewLines {
|
|
|
|
config.Out.Write(config.Formatter.FormatStatus("", ""))
|
|
|
|
}
|
2015-02-24 03:51:46 -05:00
|
|
|
}
|
|
|
|
return read, err
|
|
|
|
}
|
2015-05-27 11:48:51 -04:00
|
|
|
|
2015-02-24 03:51:46 -05:00
|
|
|
func (config *Config) Close() error {
|
2015-05-27 11:48:51 -04:00
|
|
|
if config.Current < config.Size {
|
|
|
|
//print a full progress bar when closing prematurely
|
|
|
|
config.Current = config.Size
|
|
|
|
updateProgress(config)
|
|
|
|
}
|
2015-02-24 03:51:46 -05:00
|
|
|
return config.In.Close()
|
|
|
|
}
|
2015-05-27 11:48:51 -04:00
|
|
|
|
|
|
|
func updateProgress(config *Config) {
|
|
|
|
progress := jsonmessage.JSONProgress{Current: config.Current, Total: config.Size}
|
|
|
|
fmtMessage := config.Formatter.FormatProgress(config.ID, config.Action, &progress)
|
|
|
|
config.Out.Write(fmtMessage)
|
|
|
|
}
|