github.com/jasonkeene/cli@v6.14.1-0.20160816203908-ca5715166dfb+incompatible/utils/checksum.go (about)

     1  package utils
     2  
     3  import (
     4  	"crypto/sha1"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  )
     9  
    10  //go:generate counterfeiter . Sha1Checksum
    11  
    12  type Sha1Checksum interface {
    13  	ComputeFileSha1() ([]byte, error)
    14  	CheckSha1(string) bool
    15  	SetFilePath(string)
    16  }
    17  
    18  type sha1Checksum struct {
    19  	filepath string
    20  }
    21  
    22  func NewSha1Checksum(filepath string) Sha1Checksum {
    23  	return &sha1Checksum{
    24  		filepath: filepath,
    25  	}
    26  }
    27  
    28  func (c *sha1Checksum) ComputeFileSha1() ([]byte, error) {
    29  	hash := sha1.New()
    30  
    31  	f, err := os.Open(c.filepath)
    32  	if err != nil {
    33  		return []byte{}, err
    34  	}
    35  	defer f.Close()
    36  
    37  	if _, err := io.Copy(hash, f); err != nil {
    38  		return []byte{}, err
    39  	}
    40  
    41  	return hash.Sum(nil), nil
    42  }
    43  
    44  func (c *sha1Checksum) CheckSha1(targetSha1 string) bool {
    45  	sha1, err := c.ComputeFileSha1()
    46  	if err != nil {
    47  		return false
    48  	}
    49  
    50  	if fmt.Sprintf("%x", sha1) == targetSha1 {
    51  		return true
    52  	}
    53  	return false
    54  }
    55  
    56  func (c *sha1Checksum) SetFilePath(filepath string) {
    57  	c.filepath = filepath
    58  }