1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
|
// Requires golang.org/x/tools/cmd/goyacc and modernc.org/golex
//
//go:generate goyacc -o datemath.y.go datemath.y
//go:generate golex -o datemath.l.go datemath.l
/*
Package datemath provides an expression language for relative dates based on Elasticsearch's date math.
This package is useful for letting end-users describe dates in a simple format similar to Grafana and Kibana and for
persisting them as relative dates.
The expression starts with an anchor date, which can either be "now", or an ISO8601 date string ending with ||. This
anchor date can optionally be followed by one or more date math expressions, for example:
now+1h Add one hour
now-1d Subtract one day
now/d Round down to the nearest day
The supported time units are:
y Years
M Months
w Weeks
d Days
b Business Days (excludes Saturday and Sunday by default, use WithBusinessDayFunc to override)
h Hours
H Hours
m Minutes
s Seconds
Compatibility with Elasticsearch datemath
This package aims to be a superset of Elasticsearch's expressions. That is, any datemath expression that is valid for
Elasticsearch should evaluate in the same way here.
Currently the package does not support expressions outside of those also considered valid by Elasticsearch, but this may
change in the future to include additional functionality.
*/
package datemath
import (
"fmt"
"strconv"
"strings"
"time"
)
func init() {
// have goyacc parser return more verbose syntax error messages
yyErrorVerbose = true
}
var missingTimeZone = time.FixedZone("MISSING", 0)
type timeUnit rune
const (
timeUnitYear = timeUnit('y')
timeUnitMonth = timeUnit('M')
timeUnitWeek = timeUnit('w')
timeUnitDay = timeUnit('d')
timeUnitBusinessDay = timeUnit('b')
timeUnitHour = timeUnit('h')
timeUnitMinute = timeUnit('m')
timeUnitSecond = timeUnit('s')
)
func (u timeUnit) String() string {
return string(u)
}
// Expression represents a parsed datemath expression
type Expression struct {
input string
mathExpression
}
type mathExpression struct {
anchorDateExpression anchorDateExpression
adjustments []timeAdjuster
}
func newMathExpression(anchorDateExpression anchorDateExpression, adjustments []timeAdjuster) mathExpression {
return mathExpression{
anchorDateExpression: anchorDateExpression,
adjustments: adjustments,
}
}
// MarshalJSON implements the json.Marshaler interface
//
// It serializes as the string expression the Expression was created with
func (e Expression) MarshalJSON() ([]byte, error) {
return []byte(strconv.Quote(e.String())), nil
}
// UnmarshalJSON implements the json.Unmarshaler interface
//
// Parses the datemath expression from a JSON string
func (e *Expression) UnmarshalJSON(data []byte) error {
s, err := strconv.Unquote(string(data))
if err != nil {
return err
}
expression, err := Parse(s)
if err != nil {
return nil
}
*e = expression
return nil
}
// String returns a the string used to create the expression
func (e Expression) String() string {
return e.input
}
// Options represesent configurable behavior for interpreting the datemath expression
type Options struct {
// Use this this time as "now"
// Default is `time.Now()`
Now time.Time
// Use this location if there is no timezone in the expression
// Defaults to time.UTC
Location *time.Location
// Use this weekday as the start of the week
// Defaults to time.Monday
StartOfWeek time.Weekday
// Rounding to period should be done to the end of the period
// Defaults to false
RoundUp bool
BusinessDayFunc func(time.Time) bool
}
// WithNow use the given time as "now"
func WithNow(now time.Time) func(*Options) {
return func(o *Options) {
o.Now = now
}
}
// WithStartOfWeek uses the given weekday as the start of the week
func WithStartOfWeek(day time.Weekday) func(*Options) {
return func(o *Options) {
o.StartOfWeek = day
}
}
// WithLocation uses the given location as the timezone of the date if unspecified
func WithLocation(l *time.Location) func(*Options) {
return func(o *Options) {
o.Location = l
}
}
// WithRoundUp sets the rounding of time to the end of the period instead of the beginning
func WithRoundUp(b bool) func(*Options) {
return func(o *Options) {
o.RoundUp = b
}
}
// WithBusinessDayFunc use the given fn to check if a day is a business day
func WithBusinessDayFunc(fn func(time.Time) bool) func(*Options) {
return func(o *Options) {
o.BusinessDayFunc = fn
}
}
func isNotWeekend(t time.Time) bool {
return t.Weekday() != time.Saturday && t.Weekday() != time.Sunday
}
// Time evaluate the expression with the given options to get the time it represents
func (e Expression) Time(opts ...func(*Options)) time.Time {
options := Options{
Now: time.Now(),
Location: time.UTC,
StartOfWeek: time.Monday,
}
for _, opt := range opts {
opt(&options)
}
t := e.anchorDateExpression(options)
for _, adjustment := range e.adjustments {
t = adjustment(t, options)
}
return t
}
// Parse parses the datemath expression which can later be evaluated
func Parse(s string) (Expression, error) {
lex := newLexer([]byte(s))
lexWrapper := newLexerWrapper(lex)
yyParse(lexWrapper)
if len(lex.errors) > 0 {
return Expression{}, fmt.Errorf(strings.Join(lex.errors, "\n"))
}
return Expression{input: s, mathExpression: lexWrapper.expression}, nil
}
// MustParse is the same as Parse() but panic's on error
func MustParse(s string) Expression {
e, err := Parse(s)
if err != nil {
panic(err)
}
return e
}
// ParseAndEvaluate is a convience wrapper to parse and return the time that the expression represents
func ParseAndEvaluate(s string, opts ...func(*Options)) (time.Time, error) {
expression, err := Parse(s)
if err != nil {
return time.Time{}, err
}
return expression.Time(opts...), nil
}
type anchorDateExpression func(opts Options) time.Time
func anchorDateNow(opts Options) time.Time {
return opts.Now.In(opts.Location)
}
func anchorDate(t time.Time) func(opts Options) time.Time {
return func(opts Options) time.Time {
location := t.Location()
if location == missingTimeZone {
location = opts.Location
}
return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), location)
}
}
type timeAdjuster func(time.Time, Options) time.Time
func addUnits(factor int, u timeUnit) func(time.Time, Options) time.Time {
return func(t time.Time, options Options) time.Time {
switch u {
case timeUnitYear:
return t.AddDate(factor, 0, 0)
case timeUnitMonth:
return t.AddDate(0, factor, 0)
case timeUnitWeek:
return t.AddDate(0, 0, 7*factor)
case timeUnitDay:
return t.AddDate(0, 0, factor)
case timeUnitBusinessDay:
fn := options.BusinessDayFunc
if fn == nil {
fn = isNotWeekend
}
increment := 1
if factor < 0 {
increment = -1
}
for i := factor; i != 0; i -= increment {
t = t.AddDate(0, 0, increment)
for !fn(t) {
t = t.AddDate(0, 0, increment)
}
}
return t
case timeUnitHour:
return t.Add(time.Duration(factor) * time.Hour)
case timeUnitMinute:
return t.Add(time.Duration(factor) * time.Minute)
case timeUnitSecond:
return t.Add(time.Duration(factor) * time.Second)
default:
panic(fmt.Sprintf("unknown time unit: %s", u))
}
}
}
func truncateUnits(u timeUnit) func(time.Time, Options) time.Time {
var roundDown = func(t time.Time, options Options) time.Time {
switch u {
case timeUnitYear:
return time.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location())
case timeUnitMonth:
return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
case timeUnitWeek:
diff := int(t.Weekday() - options.StartOfWeek)
if diff < 0 {
return time.Date(t.Year(), t.Month(), t.Day()+diff-1, 0, 0, 0, 0, t.Location())
}
return time.Date(t.Year(), t.Month(), t.Day()-diff, 0, 0, 0, 0, t.Location())
case timeUnitDay:
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
case timeUnitHour:
return t.Truncate(time.Hour)
case timeUnitMinute:
return t.Truncate(time.Minute)
case timeUnitSecond:
return t.Truncate(time.Second)
default:
panic(fmt.Sprintf("unknown time unit: %s", u))
}
}
return func(t time.Time, options Options) time.Time {
if options.RoundUp {
return addUnits(1, u)(roundDown(t, options), options).Add(-time.Millisecond)
}
return roundDown(t, options)
}
}
func daysIn(m time.Month, year int) int {
return time.Date(year, m+1, 0, 0, 0, 0, 0, time.UTC).Day()
}
// lexerWrapper wraps the golex generated wrapper to store the parsed expression for later and provide needed data to
// the parser
type lexerWrapper struct {
lex yyLexer
expression mathExpression
}
func newLexerWrapper(lex yyLexer) *lexerWrapper {
return &lexerWrapper{
lex: lex,
}
}
func (l *lexerWrapper) Lex(lval *yySymType) int {
return l.lex.Lex(lval)
}
func (l *lexerWrapper) Error(s string) {
l.lex.Error(s)
}
|