🚚 Move Slug/Hash Generators to own file
This commit is contained in:
parent
586fe4f1de
commit
1d0f2238b3
7 changed files with 193 additions and 162 deletions
81
gen_file.go
Normal file
81
gen_file.go
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
package nomino
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
|
||||
"github.com/gosimple/slug"
|
||||
)
|
||||
|
||||
// ErrMissingOriginal is the error returned by Slug if there is no filename
|
||||
var ErrMissingOriginal = errors.New("missing original filename")
|
||||
|
||||
func getOriginal(c *Config) (string, error) {
|
||||
if c.original == "" {
|
||||
return "", ErrMissingOriginal
|
||||
}
|
||||
name := c.original
|
||||
c.original = ""
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// Slug generates a name from the original filename.
|
||||
// When this is used, the original filename will be removed from the final filename.
|
||||
// If a language is specified, that may affect the resulting slug.
|
||||
func Slug(lang ...string) Generator {
|
||||
ret := slug.Make
|
||||
if len(lang) > 0 {
|
||||
ret = func(in string) string {
|
||||
return slug.MakeLang(in, lang[0])
|
||||
}
|
||||
}
|
||||
return func(c *Config) (string, error) {
|
||||
name, err := getOriginal(c)
|
||||
return ret(name), err
|
||||
}
|
||||
}
|
||||
|
||||
// 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,
|
||||
}
|
||||
|
||||
// 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