nomino/generators.go

71 lines
1.9 KiB
Go
Raw Normal View History

2025-03-07 17:00:38 -06:00
package nomino
import (
2025-03-10 11:47:01 -05:00
"time"
2025-03-07 17:00:38 -06:00
"github.com/google/uuid"
)
2025-03-10 11:47:01 -05:00
type generator func() (string, error)
2025-03-07 17:00:38 -06:00
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
}
2025-03-10 13:46:13 -05:00
// WithUUID sets a generator that creates a UUIDv4
2025-03-07 17:00:38 -06:00
func WithUUID() Option {
return func(c *config) {
setGenerator(c, uuidGen)
}
}
2025-03-10 11:47:01 -05:00
2025-03-10 13:46:13 -05:00
// FileTimestamp is the default format for WithTimestamp and WithTime
2025-03-10 11:47:01 -05:00
const FileTimestamp string = "2006-01-02_03-05-06-0700"
2025-03-10 13:46:13 -05:00
// WithTimestamp sets a generator that creates a date and time for the current time.
// The format is FileStamp
2025-03-10 11:47:01 -05:00
func WithTimestamp() Option {
return WithTimestampFormat(FileTimestamp)
}
2025-03-10 13:46:13 -05:00
// WithTimestampFormat sets a generator the creates a date and time for the current time with the supplied format.
2025-03-10 11:47:01 -05:00
func WithTimestampFormat(f string) Option {
return WithFormattedTime(time.Now(), f)
}
2025-03-10 13:46:13 -05:00
// WithTime sets a generator that creates a date and time for the supplied time.
// The format is FileStamp
2025-03-10 11:47:01 -05:00
func WithTime(t time.Time) Option {
return WithFormattedTime(t, FileTimestamp)
}
2025-03-10 13:46:13 -05:00
// WithFormattedTime sets a generator that creates a date and time for the supplied time with the supplied format.
2025-03-10 11:47:01 -05:00
func WithFormattedTime(t time.Time, f string) Option {
return func(c *config) {
setGenerator(c, func() (string, error) {
return t.Format(f), nil
})
}
}
2025-03-10 11:52:55 -05:00
2025-03-10 13:46:13 -05:00
// FileTimestamp is the default format for WithTimestampUTC and WithTimeUTC
2025-03-10 11:52:55 -05:00
const FileTimestampNoTZ string = "2006-01-02_03-05-06"
2025-03-10 13:46:13 -05:00
// WithTimestampUTC sets a generator the creates a date and time for the current time in UTC without a timezone in the format.
2025-03-10 11:52:55 -05:00
func WithTimestampUTC() Option {
return WithTimeUTC(time.Now())
}
2025-03-10 13:46:13 -05:00
// WithTimeUTC sets a generate that creates a date and time for the supplied time in UTC without a timezone in the format.
2025-03-10 11:52:55 -05:00
func WithTimeUTC(t time.Time) Option {
return WithFormattedTime(t.UTC(), FileTimestampNoTZ)
}