forked from raystack/optimus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
window.go
64 lines (57 loc) · 1.71 KB
/
window.go
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
package models
import (
"fmt"
"strconv"
"strings"
"time"
)
type Window interface {
Validate() error
GetStartTime(scheduleTime time.Time) (time.Time, error)
GetEndTime(scheduleTime time.Time) (time.Time, error)
GetTruncateTo() string
GetOffset() string
GetSize() string
GetVersion() int
}
func NewWindow(version int, truncateTo, offset, size string) (Window, error) {
if version == 1 {
return windowV1{truncateTo: truncateTo, offset: offset, size: size}, nil
}
if version == 2 { // nolint:gomnd
return windowV2{truncateTo: truncateTo, offset: offset, size: size}, nil
}
return nil, fmt.Errorf("window version [%d] is not recognized", version)
}
// GetEndRunDate subtract 1 day to make end inclusive
func GetEndRunDate(runTime time.Time, window Window) (time.Time, error) {
months, nonMonthDurationString, err := monthsAndNonMonthExpression(window.GetSize())
if err != nil {
return time.Time{}, err
}
nonMonthDuration, err := time.ParseDuration(nonMonthDurationString)
if err != nil {
return time.Time{}, err
}
return runTime.Add(nonMonthDuration).AddDate(0, months, 0).Add(time.Hour * -24), nil
}
func monthsAndNonMonthExpression(durationExpression string) (int, string, error) {
if strings.Contains(durationExpression, "M") == false {
return 0, durationExpression, nil
}
maxSubString := 2
splits := strings.SplitN(durationExpression, "M", maxSubString)
months, err := strconv.Atoi(splits[0])
if err != nil {
return 0, "0", err
}
// duration contains only month
if len(splits) == 1 || splits[1] == "" {
return months, "0", nil
}
// if duration is negative then use the negative duration for both the splits.
if months < 0 {
return months, "-" + splits[1], nil
}
return months, splits[1], nil
}