github.com/rakutentech/cli@v6.12.5-0.20151006231303-24468b65536e+incompatible/utils/checksum.go (about)

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