Core: use go-datemath in timerange utility (#23120)

* Core: use go-datemath in time_range

* Core: update timerange for negative epoch

* Core: update gtime component

* Core: clean up time_range tests

* Update pkg/components/gtime/gtime.go

Co-Authored-By: Arve Knudsen <arve.knudsen@gmail.com>

* Core: clean gtime tests

* components/gtime: Fix test

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>

Co-authored-by: Arve Knudsen <arve.knudsen@gmail.com>
This commit is contained in:
Agnès Toulet
2020-04-06 09:00:05 +02:00
committed by GitHub
parent 69bdcccd10
commit 56687a08f9
4 changed files with 148 additions and 52 deletions

View File

@@ -1,10 +1,11 @@
package tsdb
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/timberio/go-datemath"
)
func NewTimeRange(from, to string) *TimeRange {
@@ -79,38 +80,26 @@ func tryParseUnixMsEpoch(val string) (time.Time, bool) {
}
func (tr *TimeRange) ParseFrom() (time.Time, error) {
if res, ok := tryParseUnixMsEpoch(tr.From); ok {
return res, nil
}
fromRaw := strings.Replace(tr.From, "now-", "", 1)
diff, err := time.ParseDuration("-" + fromRaw)
if err != nil {
return time.Time{}, err
}
return tr.now.Add(diff), nil
return parse(tr.From, tr.now, false)
}
func (tr *TimeRange) ParseTo() (time.Time, error) {
if tr.To == "now" {
return tr.now, nil
} else if strings.HasPrefix(tr.To, "now-") {
withoutNow := strings.Replace(tr.To, "now-", "", 1)
return parse(tr.To, tr.now, true)
}
diff, err := time.ParseDuration("-" + withoutNow)
if err != nil {
return time.Time{}, nil
}
return tr.now.Add(diff), nil
}
if res, ok := tryParseUnixMsEpoch(tr.To); ok {
func parse(s string, now time.Time, withRoundUp bool) (time.Time, error) {
if res, ok := tryParseUnixMsEpoch(s); ok {
return res, nil
}
return time.Time{}, fmt.Errorf("cannot parse to value %s", tr.To)
withoutNow := strings.Replace(s, "now-", "", 1)
diff, err := time.ParseDuration("-" + withoutNow)
if err != nil {
return datemath.ParseAndEvaluate(s, datemath.WithNow(now), datemath.WithRoundUp(withRoundUp))
}
return now.Add(diff), nil
}
// EpochPrecisionToMs converts epoch precision to millisecond, if needed.