Skip to content

Commit 9e4439d

Browse files
optimize checksum calculation
1 parent 3190a1a commit 9e4439d

File tree

1 file changed

+9
-17
lines changed

1 file changed

+9
-17
lines changed

v2/pkgs/tools.go

+9-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,18 @@ 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+
// Check the checksum
218+
sumString := "SHA-256:" + hex.EncodeToString(h.Sum(nil))
219+
if sumString != checksum {
220+
return nil, errors.New("checksum of downloaded file doesn't match, expected: " + checksum + " got: " + sumString)
221+
}
222+
231223
// Write installed.json for retrocompatibility with v1
232224
err = writeInstalled(t.folder, path)
233225
if err != nil {

0 commit comments

Comments
 (0)