-
Notifications
You must be signed in to change notification settings - Fork 0
/
checksum.go
101 lines (77 loc) · 2.41 KB
/
checksum.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package checksum
import (
"context"
"errors"
"fmt"
"hash"
"github.com/charmbracelet/log"
"golang.org/x/sync/errgroup"
"github.com/coffeebeats/gdenv/pkg/godot/artifact"
)
var (
ErrChecksumMismatch = errors.New("checksum does not match")
ErrChecksumsUnsupported = errors.New("version precedes checksums")
)
/* -------------------------------------------------------------------------- */
/* Interface: Checksums */
/* -------------------------------------------------------------------------- */
// An interface for an 'Artifact' representing a checksums file.
type Checksums[T artifact.Artifact] interface {
artifact.Artifact
// Supports is a method to register which artifact the checksums are for.
Supports(_ T)
// Hash returns a 'hash.Hash' instance used to compute the checksum of the
// supported artifact type.
Hash() hash.Hash
}
/* -------------------------------------------------------------------------- */
/* Function: Compare */
/* -------------------------------------------------------------------------- */
// Compare takes a local executable archive and a local checksums file for
// executable archives and validates that the executable archive's checksum
// matches the expected value.
func Compare[T artifact.Artifact, U Checksums[T]](
ctx context.Context,
localArtifact artifact.Local[T],
localChecksums artifact.Local[U],
) error {
log.Info("verifying checksum of downloaded file")
eg, ctx := errgroup.WithContext(ctx)
got, want := make(chan string, 1), make(chan string, 1)
defer close(got)
defer close(want)
eg.Go(func() error {
value, err := Compute[T](ctx, localChecksums.Artifact.Hash(), localArtifact)
if err != nil {
return err
}
log.Debugf("actual checksum: %s", value)
select {
case got <- value:
case <-ctx.Done():
return ctx.Err()
}
return nil
})
eg.Go(func() error {
value, err := Extract[T](ctx, localChecksums, localArtifact.Artifact)
if err != nil {
return err
}
log.Debugf("expected checksum: %s", value)
select {
case want <- value:
case <-ctx.Done():
return ctx.Err()
}
return nil
})
if err := eg.Wait(); err != nil {
return err
}
if g, w := <-got, <-want; g != w {
return fmt.Errorf("%w: %s (got) != %s (want)", ErrChecksumMismatch, g, w)
}
log.Debug("checksum matched expected value")
return eg.Wait()
}