mirror of
https://github.com/aptly-dev/aptly.git
synced 2026-04-20 19:38:39 +00:00
Checksumming files.
This commit is contained in:
59
utils/checksum.go
Normal file
59
utils/checksum.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
type ChecksumInfo struct {
|
||||
Size int64
|
||||
MD5 string
|
||||
SHA1 string
|
||||
SHA256 string
|
||||
}
|
||||
|
||||
// ChecksumsForFile generates size, MD5, SHA1 & SHA256 checksums for given file
|
||||
func ChecksumsForFile(path string) (*ChecksumInfo, error) {
|
||||
result := &ChecksumInfo{}
|
||||
|
||||
st, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result.Size = st.Size()
|
||||
|
||||
hashes := []hash.Hash{md5.New(), sha1.New(), sha256.New()}
|
||||
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
buf := make([]byte, 8192)
|
||||
for {
|
||||
n, err := file.Read(buf)
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, h := range hashes {
|
||||
h.Write(buf[:n])
|
||||
}
|
||||
}
|
||||
|
||||
result.MD5 = fmt.Sprintf("%x", hashes[0].Sum(nil))
|
||||
result.SHA1 = fmt.Sprintf("%x", hashes[1].Sum(nil))
|
||||
result.SHA256 = fmt.Sprintf("%x", hashes[2].Sum(nil))
|
||||
|
||||
return result, nil
|
||||
}
|
||||
32
utils/checksum_test.go
Normal file
32
utils/checksum_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
. "launchpad.net/gocheck"
|
||||
"os"
|
||||
)
|
||||
|
||||
type ChecksumSuite struct {
|
||||
tempfile *os.File
|
||||
}
|
||||
|
||||
var _ = Suite(&ChecksumSuite{})
|
||||
|
||||
func (s *ChecksumSuite) SetUpTest(c *C) {
|
||||
s.tempfile, _ = ioutil.TempFile(c.MkDir(), "aptly-test")
|
||||
s.tempfile.WriteString("Quick brown fox jumps over black dog and runs away... Really far away... who knows?")
|
||||
}
|
||||
|
||||
func (s *ChecksumSuite) TearDownTest(c *C) {
|
||||
s.tempfile.Close()
|
||||
}
|
||||
|
||||
func (s *ChecksumSuite) TestChecksum(c *C) {
|
||||
info, err := ChecksumsForFile(s.tempfile.Name())
|
||||
|
||||
c.Assert(err, IsNil)
|
||||
c.Check(info.Size, Equals, int64(83))
|
||||
c.Check(info.MD5, Equals, "43470766afbfdca292440eecdceb80fb")
|
||||
c.Check(info.SHA1, Equals, "1743f8408261b4f1eff88e0fca15a7077223fa79")
|
||||
c.Check(info.SHA256, Equals, "f2775692fd3b70bd0faa4054b7afa92d427bf994cd8629741710c4864ee4dc95")
|
||||
}
|
||||
Reference in New Issue
Block a user