♻️ Replace HashType with Hasher
Compatible with crypto.Hash
This commit is contained in:
parent
1008a064d0
commit
2440f55563
5 changed files with 47 additions and 95 deletions
46
gen_file.go
46
gen_file.go
|
|
@ -1,9 +1,7 @@
|
|||
package nomino
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"crypto"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
|
|
@ -42,39 +40,35 @@ func Slug(lang ...string) Generator {
|
|||
// HashingFunc is a function that generates a hash.Hash
|
||||
type HashingFunc func() hash.Hash
|
||||
|
||||
//go:generate stringer -type=HashType -trimprefix=Hash
|
||||
|
||||
// HashType represents a particular hashing algorithm
|
||||
type HashType uint8
|
||||
|
||||
const (
|
||||
HashMD5 HashType = iota + 1
|
||||
HashSHA1
|
||||
HashSHA256
|
||||
)
|
||||
|
||||
// ErrInvalidHashType is returned by the Hash generator when an invalid HashType is passed
|
||||
var ErrInvalidHashType = errors.New("invalid hash type")
|
||||
|
||||
var hashMap = map[HashType]HashingFunc{
|
||||
HashMD5: md5.New,
|
||||
HashSHA1: sha1.New,
|
||||
HashSHA256: sha256.New,
|
||||
// New allows HashingFunc to be used as a Hasher
|
||||
func (hf HashingFunc) New() hash.Hash {
|
||||
return hf()
|
||||
}
|
||||
|
||||
// Hasher is a type returns a hash.Hash.
|
||||
// All crypto.Hash may be used.
|
||||
type Hasher interface {
|
||||
New() hash.Hash
|
||||
}
|
||||
|
||||
// ErrInvalidHash is returned by the Hash generator when an invalid HashType is passed
|
||||
var ErrInvalidHash = errors.New("invalid hash type")
|
||||
|
||||
// Hash generates a name from a hash of the filename.
|
||||
// When this is used, the original filename will be removed from the final filename.
|
||||
func Hash(t HashType) Generator {
|
||||
f, ok := hashMap[t]
|
||||
func Hash(h Hasher) Generator {
|
||||
if h == nil {
|
||||
h = crypto.MD5
|
||||
}
|
||||
return func(c *Config) (string, error) {
|
||||
if !ok {
|
||||
return "", fmt.Errorf("%w: %s", ErrInvalidHashType, t)
|
||||
if h == crypto.MD5SHA1 {
|
||||
return "", ErrInvalidHash
|
||||
}
|
||||
name, err := getOriginal(c)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
hs := f()
|
||||
hs := h.New()
|
||||
hs.Write([]byte(name))
|
||||
return fmt.Sprintf("%x", hs.Sum(nil)), nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue