Skip to content

Commit

Permalink
Merge pull request hashicorp#168 from hashicorp/type_checksum_error
Browse files Browse the repository at this point in the history
add a public type for a checksum error
  • Loading branch information
azr authored Mar 6, 2019
2 parents 0be63f2 + 61d37e4 commit e1437d0
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions checksum.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,27 @@ type fileChecksum struct {
Filename string
}

// A ChecksumError is returned when a checksum differs
type ChecksumError struct {
Hash hash.Hash
Actual []byte
Expected []byte
File string
}

func (cerr *ChecksumError) Error() string {
if cerr == nil {
return "<nil>"
}
return fmt.Sprintf(
"Checksums did not match for %s.\nExpected: %s\nGot: %s\n%T",
cerr.File,
hex.EncodeToString(cerr.Expected),
hex.EncodeToString(cerr.Actual),
cerr.Hash, // ex: *sha256.digest
)
}

// checksum is a simple method to compute the checksum of a source file
// and compare it to the given expected value.
func (c *fileChecksum) checksum(source string) error {
Expand All @@ -42,10 +63,12 @@ func (c *fileChecksum) checksum(source string) error {
}

if actual := c.Hash.Sum(nil); !bytes.Equal(actual, c.Value) {
return fmt.Errorf(
"Checksums did not match.\nExpected: %s\nGot: %s",
hex.EncodeToString(c.Value),
hex.EncodeToString(actual))
return &ChecksumError{
Hash: c.Hash,
Actual: actual,
Expected: c.Value,
File: source,
}
}

return nil
Expand Down

0 comments on commit e1437d0

Please sign in to comment.