✨ Add Hash generator
This commit is contained in:
parent
dd531c1f73
commit
8888ee3855
5 changed files with 124 additions and 1 deletions
|
|
@ -1,8 +1,12 @@
|
|||
package nomino
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
|
|
@ -185,3 +189,44 @@ func SlugWithLang(lang string) Generator {
|
|||
return slug.MakeLang(name, lang), err
|
||||
}
|
||||
}
|
||||
|
||||
// HashingFunc is a function that generates a hash.Hash
|
||||
type HashingFunc func() hash.Hash
|
||||
|
||||
//go:generate stringer -type=HashType
|
||||
|
||||
// HashType represents a particular hashing algorithm
|
||||
type HashType uint8
|
||||
|
||||
const (
|
||||
MD5 HashType = iota + 1
|
||||
SHA1
|
||||
SHA256
|
||||
)
|
||||
|
||||
// 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{
|
||||
MD5: md5.New,
|
||||
SHA1: sha1.New,
|
||||
SHA256: sha256.New,
|
||||
}
|
||||
|
||||
// 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]
|
||||
return func(c *Config) (string, error) {
|
||||
if !ok {
|
||||
return "", fmt.Errorf("%w: %s", ErrInvalidHashType, t)
|
||||
}
|
||||
name, err := getOriginal(c)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
hs := f()
|
||||
hs.Write([]byte(name))
|
||||
return fmt.Sprintf("%x", hs.Sum(nil)), nil
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue