@cryptotaxi247 / kubo / commits / 169f7899b

fix progress bar on ipfs get

License: MIT Signed-off-by: Jeromy <jeromyj@gmail.com>

Jeromy committed Mar 6, 2017 at 22:58 UTC 169f7899ba0cfc9a6e24061790b893e015972998
2 files changed +34 -7
core/commands/get.go
+11 -5
@@ -143,6 +143,12 @@ func (r *clearlineReader) Read(p []byte) (n int, err error) {
143 }
144
145 func progressBarForReader(out io.Writer, r io.Reader, l int64) (*pb.ProgressBar, io.Reader) {
146 + bar := makeProgressBar(out, l)
147 + barR := bar.NewProxyReader(r)
148 + return bar, &clearlineReader{barR, out}
149 +}
150 +
151 +func makeProgressBar(out io.Writer, l int64) *pb.ProgressBar {
152 // setup bar reader
153 // TODO: get total length of files
154 bar := pb.New64(l).SetUnits(pb.U_BYTES)
@@ -155,8 +161,7 @@ func progressBarForReader(out io.Writer, r io.Reader, l int64) (*pb.ProgressBar,
161 bar.Callback = nil
162 log.Infof("terminal width: %v\n", terminalWidth)
163 }
158 - barR := bar.NewProxyReader(r)
159 - return bar, &clearlineReader{barR, out}
164 + return bar
165 }
166
167 type getWriter struct {
@@ -208,12 +213,13 @@ func (gw *getWriter) writeArchive(r io.Reader, fpath string) error {
213
214 func (gw *getWriter) writeExtracted(r io.Reader, fpath string) error {
215 fmt.Fprintf(gw.Out, "Saving file(s) to %s\n", fpath)
211 - bar, barR := progressBarForReader(gw.Err, r, gw.Size)
216 + bar := makeProgressBar(gw.Err, gw.Size)
217 bar.Start()
218 defer bar.Finish()
219 + defer bar.Set64(gw.Size)
220
215 - extractor := &tar.Extractor{fpath}
216 - return extractor.Extract(barR)
221 + extractor := &tar.Extractor{fpath, bar.Add64}
222 + return extractor.Extract(r)
223 }
224
225 func getCompressOptions(req cmds.Request) (int, error) {
thirdparty/tar/extractor.go
+23 -2
@@ -11,7 +11,8 @@ import (
11 )
12
13 type Extractor struct {
14 - Path string
14 + Path string
15 + Progress func(int64) int64
16 }
17
18 func (te *Extractor) Extract(reader io.Reader) error {
@@ -111,10 +112,30 @@ func (te *Extractor) extractFile(h *tar.Header, r *tar.Reader, depth int, rootEx
112 }
113 defer file.Close()
114
114 - _, err = io.Copy(file, r)
115 + err = copyWithProgress(file, r, te.Progress)
116 if err != nil {
117 return err
118 }
119
120 return nil
121 }
122 +
123 +func copyWithProgress(to io.Writer, from io.Reader, cb func(int64) int64) error {
124 + buf := make([]byte, 4096)
125 + for {
126 + n, err := from.Read(buf)
127 + if err != nil {
128 + if err == io.EOF {
129 + return nil
130 + }
131 + return err
132 + }
133 +
134 + cb(int64(n))
135 + _, err = to.Write(buf[:n])
136 + if err != nil {
137 + return err
138 + }
139 + }
140 +
141 +}