nomino/generators.go

59 lines
1.3 KiB
Go
Raw Normal View History

2025-03-07 17:00:38 -06:00
package nomino
import (
2025-03-10 14:25:00 -05:00
"errors"
2025-03-10 11:47:01 -05:00
2025-03-07 17:00:38 -06:00
"github.com/google/uuid"
)
// Generator is a function that returns the "random" portion of the returned filename.
// Technically, it doesn't necessarily need to be random, and could be based on time, or a counter,
// for example.
2025-03-13 15:36:30 -05:00
type Generator func(conf *Config) (string, error)
2025-03-10 11:47:01 -05:00
// WithGenerator sets the specified generator
func WithGenerator(g Generator) Option {
2025-03-10 14:52:50 -05:00
return func(c *Config) {
c.generator = g
}
2025-03-07 17:00:38 -06:00
}
2025-03-10 14:25:00 -05:00
// ErrMissingGenerators is returned by a multi-generator if no generators are supplied.
var ErrMissingGenerators = errors.New("no generators supplied")
2025-03-13 15:36:30 -05:00
func missingGen(*Config) (string, error) {
2025-03-10 14:25:00 -05:00
return "", ErrMissingGenerators
}
// MultiGeneratorInOrder allows the use of multiple generators. Each new invokation will use the next generator in turn.
// If none are passed, the generator will always return ErrMissingGenerators.
func MultiGeneratorInOrder(gens ...Generator) Generator {
if len(gens) == 0 {
return missingGen
}
if len(gens) == 1 {
return gens[0]
}
var idx int
2025-03-13 15:36:30 -05:00
return func(c *Config) (string, error) {
st, err := gens[idx](c)
2025-03-10 14:25:00 -05:00
idx = (idx + 1) % len(gens)
return st, err
}
}
2025-03-13 15:36:30 -05:00
func uuidGen(*Config) (string, error) {
2025-03-07 17:00:38 -06:00
u, err := uuid.NewRandom()
if err != nil {
return "", err
}
return u.String(), nil
}
// UUID generates a UUIDv4.
func UUID() Generator {
return uuidGen
2025-03-07 17:00:38 -06:00
}