Skip to content

Commit e5a30f6

Browse files
optimize checksum calculation
1 parent 3190a1a commit e5a30f6

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

v2/pkgs/tools.go

+14-17
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
package pkgs
1717

1818
import (
19-
"bytes"
2019
"context"
2120
"crypto/sha256"
2221
"encoding/hex"
@@ -195,21 +194,8 @@ func (t *Tools) install(ctx context.Context, path, url, checksum string) (*tools
195194
}
196195
defer res.Body.Close()
197196

198-
var buffer bytes.Buffer
199-
200-
// We copy the body of the response to a buffer to calculate the checksum
201-
_, err = io.Copy(&buffer, res.Body)
202-
if err != nil {
203-
return nil, err
204-
}
205-
206-
// Check the checksum
207-
sum := sha256.Sum256(buffer.Bytes())
208-
sumString := "SHA-256:" + hex.EncodeToString(sum[:sha256.Size])
209-
210-
if sumString != checksum {
211-
return nil, errors.New("checksum of downloaded file doesn't match, expected: " + checksum + " got: " + sumString)
212-
}
197+
h := sha256.New()
198+
r := io.TeeReader(res.Body, h)
213199

214200
safePath, err := utilities.SafeJoin(t.folder, path)
215201
if err != nil {
@@ -222,12 +208,23 @@ func (t *Tools) install(ctx context.Context, path, url, checksum string) (*tools
222208
return nil, err
223209
}
224210

225-
err = extract.Archive(ctx, &buffer, t.folder, rename(path))
211+
err = extract.Archive(ctx, r, t.folder, rename(path))
226212
if err != nil {
227213
os.RemoveAll(safePath)
228214
return nil, err
229215
}
230216

217+
buf := []byte{}
218+
if n, err := r.Read(buf); err != io.EOF {
219+
fmt.Println("Error: expected EOF %v", n)
220+
}
221+
222+
// Check the checksum
223+
sumString := "SHA-256:" + hex.EncodeToString(h.Sum(nil))
224+
if sumString != checksum {
225+
return nil, errors.New("checksum of downloaded file doesn't match, expected: " + checksum + " got: " + sumString)
226+
}
227+
231228
// Write installed.json for retrocompatibility with v1
232229
err = writeInstalled(t.folder, path)
233230
if err != nil {

0 commit comments

Comments
 (0)