github.com/pkalwak/bagins@v0.0.0-20210317172317-694ac5ce2f54/bagutil.go (about)

     1  /*
     2  Package contains various utility methods to work with bagit bags.
     3  
     4  */
     5  package bagins
     6  
     7  /*
     8  
     9  "Deeds will not be less valiant because they are unpraised."
    10  
    11  - Aragorn
    12  
    13  */
    14  
    15  import (
    16  	"crypto"
    17  	_ "crypto/md5"
    18  	_ "crypto/sha1"
    19  	_ "crypto/sha256"
    20  	_ "crypto/sha512"
    21  	"fmt"
    22  	"hash"
    23  	"io"
    24  	"os"
    25  	"strings"
    26  )
    27  
    28  // Performs a checksum with the hsh.Hash.Sum() method passed to the function
    29  // and returns the hex value of the resultant string or an error
    30  func FileChecksum(filepath string, hsh hash.Hash) (string, error) {
    31  	src, err := FS.Open(filepath)
    32  	if err != nil {
    33  		return "", err
    34  	}
    35  	defer src.Close()
    36  
    37  	_, err = io.Copy(hsh, src)
    38  	if err != nil {
    39  		return "", err
    40  	}
    41  	return fmt.Sprintf("%x", hsh.Sum(nil)), nil
    42  }
    43  
    44  // Utility method to return the operation system seperator as a string.
    45  func PathSeparator() string {
    46  	return string(byte(os.PathSeparator))
    47  }
    48  
    49  // Returns a new hash function based on a lookup of the algo string
    50  // passed to the function.  Returns an error if the algo string does not match
    51  // any of the available cryto hashes.
    52  func LookupHash(algo string) (func() hash.Hash, error) {
    53  	switch strings.ToLower(algo) {
    54  	case "md5":
    55  		return crypto.MD5.New, nil
    56  	case "sha1":
    57  		return crypto.SHA1.New, nil
    58  	case "sha256":
    59  		return crypto.SHA256.New, nil
    60  	case "sha512":
    61  		return crypto.SHA512.New, nil
    62  	case "sha224":
    63  		return crypto.SHA224.New, nil
    64  	case "sha384":
    65  		return crypto.SHA384.New, nil
    66  	}
    67  	return nil, fmt.Errorf("Invalid hash name %s: "+
    68  		"Must be one of md5, sha1, sha256, sha512, sha224, sha284. "+
    69  		"Do you have a manifest-%s.txt file somewhere in your bag?",
    70  		algo, algo)
    71  }