72 lines
2 KiB
Go
72 lines
2 KiB
Go
package nomino
|
|
|
|
import (
|
|
"time"
|
|
|
|
"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.
|
|
type Generator func() (string, error)
|
|
|
|
// WithGenerator sets the specified generator
|
|
func WithGenerator(g Generator) Option {
|
|
return func(c *config) {
|
|
c.generator = g
|
|
}
|
|
}
|
|
|
|
func uuidGen() (string, error) {
|
|
u, err := uuid.NewRandom()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return u.String(), nil
|
|
}
|
|
|
|
// UUID generates a UUIDv4.
|
|
func UUID() Generator {
|
|
return uuidGen
|
|
}
|
|
|
|
// FileTimestamp is the default format for WithTimestamp and WithTime
|
|
const FileTimestamp string = "2006-01-02_03-05-06-0700"
|
|
|
|
// Timestamp generates a a date and time for the current time.
|
|
// It is formatted accourding to FileTimestamp
|
|
func Timestamp() Generator {
|
|
return TimestampWithFormat(FileTimestamp)
|
|
}
|
|
|
|
// TimestampWithFormat generates a date and time for the current time with the supplied format.
|
|
func TimestampWithFormat(f string) Generator {
|
|
return FormattedTime(time.Now(), FileTimestamp)
|
|
}
|
|
|
|
// Time generates a date and time for the supplied time.
|
|
// It is formatted accourding to FileTimestamp
|
|
func Time(t time.Time) Generator {
|
|
return FormattedTime(t, FileTimestamp)
|
|
}
|
|
|
|
// FormattedTime generates a date and time for the supplied time with the supplied format.
|
|
func FormattedTime(t time.Time, f string) Generator {
|
|
return 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"
|
|
|
|
// TimestampUTC generates a date and time for the current time in UTC without a timezone in the format.
|
|
func TimestampUTC() Generator {
|
|
return TimeUTC(time.Now())
|
|
}
|
|
|
|
// TimeUTC generates a date and time for the supplied time in UTC without a timezone in the format.
|
|
func TimeUTC(t time.Time) Generator {
|
|
return FormattedTime(t.UTC(), FileTimestampNoTZ)
|
|
}
|