nomino/generators.go
2025-03-10 13:46:13 -05:00

70 lines
1.9 KiB
Go

package nomino
import (
"time"
"github.com/google/uuid"
)
type generator func() (string, error)
func setGenerator(c *config, g generator) {
c.generator = g
}
func uuidGen() (string, error) {
u, err := uuid.NewRandom()
if err != nil {
return "", err
}
return u.String(), nil
}
// WithUUID sets a generator that creates a UUIDv4
func WithUUID() Option {
return func(c *config) {
setGenerator(c, uuidGen)
}
}
// FileTimestamp is the default format for WithTimestamp and WithTime
const FileTimestamp string = "2006-01-02_03-05-06-0700"
// WithTimestamp sets a generator that creates a date and time for the current time.
// The format is FileStamp
func WithTimestamp() Option {
return WithTimestampFormat(FileTimestamp)
}
// WithTimestampFormat sets a generator the creates a date and time for the current time with the supplied format.
func WithTimestampFormat(f string) Option {
return WithFormattedTime(time.Now(), f)
}
// WithTime sets a generator that creates a date and time for the supplied time.
// The format is FileStamp
func WithTime(t time.Time) Option {
return WithFormattedTime(t, FileTimestamp)
}
// WithFormattedTime sets a generator that creates a date and time for the supplied time with the supplied format.
func WithFormattedTime(t time.Time, f string) Option {
return func(c *config) {
setGenerator(c, func() (string, error) {
return t.Format(f), nil
})
}
}
// FileTimestamp is the default format for WithTimestampUTC and WithTimeUTC
const FileTimestampNoTZ string = "2006-01-02_03-05-06"
// WithTimestampUTC sets a generator the creates a date and time for the current time in UTC without a timezone in the format.
func WithTimestampUTC() Option {
return WithTimeUTC(time.Now())
}
// WithTimeUTC sets a generate that creates a date and time for the supplied time in UTC without a timezone in the format.
func WithTimeUTC(t time.Time) Option {
return WithFormattedTime(t.UTC(), FileTimestampNoTZ)
}