generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
pattern.go
299 lines (265 loc) · 7.1 KB
/
pattern.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
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
package cron
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer"
"github.com/TBD54566975/ftl/internal/duration"
"github.com/TBD54566975/ftl/internal/slices"
)
var (
lex = lexer.MustSimple([]lexer.SimpleRule{
{Name: "Whitespace", Pattern: `\s+`},
{Name: "Ident", Pattern: `\b[a-zA-Z_][a-zA-Z0-9_]*\b`},
{Name: "Comment", Pattern: `//.*`},
{Name: "String", Pattern: `"(?:\\.|[^"])*"`},
{Name: "Number", Pattern: `[0-9]+(?:\.[0-9]+)?`},
{Name: "Punct", Pattern: `[%/\-\_:[\]{}<>()*+?.,\\^$|#~!\'@]`},
})
parserOptions = []participle.Option{
participle.Lexer(lex),
participle.CaseInsensitive("Ident"),
participle.Elide("Whitespace"),
participle.Unquote(),
participle.Map(func(token lexer.Token) (lexer.Token, error) {
token.Value = strings.TrimSpace(strings.TrimPrefix(token.Value, "//"))
return token, nil
}, "Comment"),
}
parser = participle.MustBuild[Pattern](parserOptions...)
)
type Pattern struct {
Duration *string `parser:"@(Number ('s' | 'm' | 'h'))"`
DayOfWeek *DayOfWeek `parser:"| @('Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri' | 'Sat' | 'Sun')"`
Components []Component `parser:"| @@+"`
}
func (p Pattern) String() string {
if p.Duration != nil {
return *p.Duration
}
if p.DayOfWeek != nil {
return string(*p.DayOfWeek)
}
return strings.Join(slices.Map(p.Components, func(component Component) string {
return component.String()
}), " ")
}
func (p Pattern) standardizedComponents() ([]Component, error) {
if p.Duration != nil {
parsed, err := duration.ParseComponents(*p.Duration)
if err != nil {
return nil, err
}
// Do not allow durations with days, as it is confusing for the user.
if parsed.Days > 0 {
return nil, fmt.Errorf("durations with days are not allowed")
}
ss := newShortState()
ss.push(parsed.Seconds)
ss.push(parsed.Minutes)
ss.push(parsed.Hours)
ss.full() // Day of month
ss.full() // Month
ss.full() // Day of week
ss.full() // Year
return ss.done()
}
if p.DayOfWeek != nil {
dayOfWeekInt, err := p.DayOfWeek.toInt()
if err != nil {
return nil, err
}
components := newComponentsFilled()
components[0] = newComponentWithValue(0) // seconds
components[1] = newComponentWithValue(0) // minutes
components[2] = newComponentWithValue(0) // hours
components[5] = newComponentWithValue(dayOfWeekInt)
return components, nil
}
switch len(p.Components) {
case 5:
// Convert "a b c d e" -> "0 a b c d e *"
components := make([]Component, 7)
components[0] = newComponentWithValue(0)
copy(components[1:], p.Components)
components[6] = newComponentWithFullRange()
return components, nil
case 6:
// Might be two different formats unfortunately.
// Could be:
// - seconds, minutes, hours, day of month, month, day of week
// - minutes, hours, day of month, month, day of week, year
// Detect by looking for 4 digit numbers in the last component, and then treat it as a year column
if isComponentLikelyToBeYearComponent(p.Components[5]) {
// Convert "a b c d e f" -> "0 a b c d e f"
components := make([]Component, 7)
components[0] = newComponentWithValue(0)
copy(components[1:], p.Components)
return components, nil
} else {
// Convert "a b c d e f" -> "a b c d e f *"
components := make([]Component, 7)
copy(components[0:], p.Components)
components[6] = newComponentWithFullRange()
return components, nil
}
case 7:
return p.Components, nil
default:
return nil, fmt.Errorf("expected 5-7 components, got %d", len(p.Components))
}
}
func isComponentLikelyToBeYearComponent(component Component) bool {
for _, s := range component.List {
if s.ValueRange.Start != nil && *s.ValueRange.Start >= 1000 {
return true
}
if s.ValueRange.End != nil && *s.ValueRange.End >= 1000 {
return true
}
}
return false
}
type Component struct {
List []Step `parser:"(@@ (',' @@)*)"`
}
func newComponentsFilled() []Component {
var c []Component
for range 7 {
c = append(c, newComponentWithFullRange())
}
return c
}
func newComponentWithFullRange() Component {
return Component{
List: []Step{
{
ValueRange: ValueRange{IsFullRange: true},
},
},
}
}
func newComponentWithValue(value int) Component {
return Component{
List: []Step{
newStepWithValue(value),
},
}
}
func newComponentWithStep(value int) Component {
var step Step
step.Step = &value
step.ValueRange.IsFullRange = true
return Component{
List: []Step{step},
}
}
func (c Component) String() string {
return strings.Join(slices.Map(c.List, func(step Step) string {
return step.String()
}), ",")
}
type Step struct {
ValueRange ValueRange `parser:"@@"`
Step *int `parser:"('/' @Number)?"`
}
func newStepWithValue(value int) Step {
return Step{
ValueRange: ValueRange{Start: &value, End: nil},
}
}
func (s *Step) String() string {
if s.Step != nil {
return fmt.Sprintf("%s/%d", s.ValueRange.String(), *s.Step)
}
return s.ValueRange.String()
}
type ValueRange struct {
IsFullRange bool `parser:"(@'*'"`
Start *int `parser:"| @Number"`
End *int `parser:"('-' @Number)?)"`
}
func (r *ValueRange) String() string {
if r.IsFullRange {
return "*"
}
if r.End != nil {
return fmt.Sprintf("%d-%d", *r.Start, *r.End)
}
return strconv.Itoa(*r.Start)
}
func Parse(text string) (Pattern, error) {
pattern, err := parser.ParseString("", text)
if err != nil {
return Pattern{}, err
}
// Validate to make sure that a pattern has no mistakes in the cron format, and that there is a valid next value from a set point in time
_, err = NextAfter(*pattern, time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), true)
if err != nil {
return Pattern{}, err
}
return *pattern, nil
}
// A helper struct to build up a cron pattern with a short syntax.
type shortState struct {
seenNonZero bool
components []Component
err error
}
func newShortState() shortState {
return shortState{
seenNonZero: false,
components: make([]Component, 0, 7),
}
}
func (ss *shortState) push(value int) {
var component Component
if value == 0 {
if ss.seenNonZero {
component = newComponentWithFullRange()
} else {
component = newComponentWithValue(value)
}
} else {
if ss.seenNonZero {
ss.err = fmt.Errorf("only one non-zero component is allowed")
}
ss.seenNonZero = true
component = newComponentWithStep(value)
}
ss.components = append(ss.components, component)
}
func (ss *shortState) full() {
ss.components = append(ss.components, newComponentWithFullRange())
}
func (ss shortState) done() ([]Component, error) {
if ss.err != nil {
return nil, ss.err
}
return ss.components, nil
}
type DayOfWeek string
// toInt converts a DayOfWeek to an integer, where Sunday is 0 and Saturday is 6.
// Case insensitively check the first three characters to match.
func (d *DayOfWeek) toInt() (int, error) {
switch strings.ToLower(string(*d)[:3]) {
case "sun":
return 0, nil
case "mon":
return 1, nil
case "tue":
return 2, nil
case "wed":
return 3, nil
case "thu":
return 4, nil
case "fri":
return 5, nil
case "sat":
return 6, nil
default:
return 0, fmt.Errorf("invalid day of week: %q", *d)
}
}