Add generic content digest tool

Previously a useful gist, this changeset polishes the original tarsum tool into
a utility that can be used to calculate content digests. Any algorithm from the
digest package is supported with additional support from tarsum.

This tool is very useful for quickly checking backend digests and verifying
correctness.

Signed-off-by: Stephen J Day <stephen.day@docker.com>
This commit is contained in:
Stephen J Day 2015-08-20 12:39:50 -07:00
parent e4b93d1e6d
commit 7835d261d8
4 changed files with 165 additions and 9 deletions

View file

@ -3,6 +3,7 @@ package digest
import (
"crypto"
"hash"
"io"
)
// Algorithm identifies and implementation of a digester by an identifier.
@ -49,6 +50,22 @@ func (a Algorithm) Available() bool {
return h.Available()
}
func (a Algorithm) String() string {
return string(a)
}
// Set implemented to allow use of Algorithm as a command line flag.
func (a *Algorithm) Set(value string) error {
if value == "" {
*a = Canonical
} else {
// just do a type conversion, support is queried with Available.
*a = Algorithm(value)
}
return nil
}
// New returns a new digester for the specified algorithm. If the algorithm
// does not have a digester implementation, nil will be returned. This can be
// checked by calling Available before calling New.
@ -69,6 +86,17 @@ func (a Algorithm) Hash() hash.Hash {
return algorithms[a].New()
}
// FromReader returns the digest of the reader using the algorithm.
func (a Algorithm) FromReader(rd io.Reader) (Digest, error) {
digester := a.New()
if _, err := io.Copy(digester.Hash(), rd); err != nil {
return "", err
}
return digester.Digest(), nil
}
// TODO(stevvooe): Allow resolution of verifiers using the digest type and
// this registration system.