-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathparse.go
383 lines (338 loc) · 8.13 KB
/
parse.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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package rrule
import (
"bufio"
"bytes"
"errors"
"fmt"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
)
// ParseRecurrence parses a whole recurrence from an iCalendar object. iCalendar
// properties recognized are DTSTART, RRULE, EXRULE, RDATE, EXDATE. Others are
// ignored.
//
// loc defines what "local" means to the parsed rules. Some patterns may
// specify a "floating" time, one without a timezone or offset, which matches
// a different actual time in different timezones. For example,
//
// RRULE:FREQ=YEARLY;BYSECOND=-10
//
// might be useful to alert you to start counting down to the new year, no
// matter your timezone. A rule with a specific timezone, however,
//
// DTSTART;TZID=America/New_York:19991231T000000
// RRULE:FREQ=YEARLY;BYSECOND=-10
//
// would track a specific timezone and ignore loc. This example would alert you
// to count down to the ball dropping in New York's Times Square for each new year.
//
// If nil, time.UTC will be used.
func ParseRecurrence(src []byte, loc *time.Location) (*Recurrence, error) {
scanner := bufio.NewScanner(bytes.NewBuffer(src))
recurrence := &Recurrence{}
for scanner.Scan() {
text := scanner.Text()
colonIdx := strings.IndexAny(text, ":;")
if colonIdx < 0 || len(text)-1 == colonIdx {
return nil, fmt.Errorf("misformatted line %q", text)
}
propName := text[:colonIdx]
propVal := text[colonIdx+1:]
switch propName {
case "DTSTART":
t, floating, err := parseTime(text, loc)
if err != nil {
return nil, err
}
recurrence.Dtstart = t
recurrence.FloatingLocation = floating
case "RRULE":
rrule, err := ParseRRule(propVal)
if err != nil {
return nil, err
}
recurrence.RRules = append(recurrence.RRules, rrule)
case "EXRULE":
rrule, err := ParseRRule(propVal)
if err != nil {
return nil, err
}
recurrence.ExRules = append(recurrence.ExRules, rrule)
case "RDATE":
t, _, err := parseTime(propVal, loc)
if err != nil {
return nil, err
}
recurrence.RDates = append(recurrence.RDates, t)
case "EXDATE":
t, _, err := parseTime(propVal, loc)
if err != nil {
return nil, err
}
recurrence.ExDates = append(recurrence.ExDates, t)
}
}
recurrence.setDtstart()
return recurrence, nil
}
// ParseRRule parses a single RRule pattern.
func ParseRRule(str string) (RRule, error) {
scanner := bufio.NewScanner(bytes.NewBufferString(str))
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if idx := bytes.Index(data, []byte{';'}); idx >= 0 {
return idx + 1, data[:idx], nil
}
if atEOF {
return len(data), data, nil
}
return 0, nil, nil
})
rrule := RRule{}
for scanner.Scan() {
wholeComponent := scanner.Text()
parts := strings.SplitN(wholeComponent, "=", 2)
if len(parts) < 2 {
return rrule, fmt.Errorf("rrule segment %q is invalid", scanner.Text())
}
directive, value := parts[0], parts[1]
switch strings.ToUpper(directive) {
case "FREQ":
freq, err := strToFreq(value)
if err != nil {
return rrule, err
}
rrule.Frequency = freq
case "UNTIL":
t, floating, err := parseTime(wholeComponent, nil)
if err != nil {
return rrule, err
}
rrule.Until = t
rrule.UntilFloating = floating
case "COUNT":
i, err := strconv.Atoi(value)
if err != nil {
return rrule, err
}
rrule.Count = uint64(i)
case "INTERVAL":
i, err := strconv.Atoi(value)
if err != nil {
return rrule, err
}
rrule.Interval = i
case "BYSECOND":
ints, err := parseInts(value, 0, 60, true)
if err != nil {
return rrule, err
}
rrule.BySeconds = ints
case "BYMINUTE":
ints, err := parseInts(value, 0, 59, true)
if err != nil {
return rrule, err
}
rrule.ByMinutes = ints
case "BYHOUR":
ints, err := parseInts(value, 0, 23, true)
if err != nil {
return rrule, err
}
rrule.ByHours = ints
case "BYDAY":
wds, err := parseQualifiedWeekdays(value)
if err != nil {
return rrule, err
}
rrule.ByWeekdays = wds
case "BYMONTHDAY":
ints, err := parseInts(value, -31, 31, false)
if err != nil {
return rrule, err
}
rrule.ByMonthDays = ints
case "BYYEARDAY":
ints, err := parseInts(value, -366, 366, true)
if err != nil {
return rrule, err
}
rrule.ByYearDays = ints
case "BYWEEKNO":
ints, err := parseInts(value, -53, 53, false)
if err != nil {
return rrule, err
}
rrule.ByWeekNumbers = ints
case "BYMONTH":
months, err := parseMonths(value)
if err != nil {
return rrule, err
}
rrule.ByMonths = months
case "BYSETPOS":
ints, err := parseInts(value, -366, 366, false)
if err != nil {
return rrule, err
}
rrule.BySetPos = ints
case "WKST":
wd, err := parseWeekday(value)
if err != nil {
return rrule, err
}
rrule.WeekStart = &wd
case "SKIP":
skip, err := parseSkip(value)
if err != nil {
return rrule, err
}
rrule.InvalidBehavior = skip
case "RSCALE":
err := parseRScale(value)
if err != nil {
return rrule, err
}
default:
return rrule, fmt.Errorf("%q is not a supported RRULE part", directive)
}
}
err := rrule.Validate()
return rrule, err
}
func parseInts(str string, min, max int, allowZero bool) ([]int, error) {
if len(str) == 0 {
return nil, nil
}
var err error
parts := strings.Split(str, ",")
ints := make([]int, len(parts))
for i, p := range parts {
var currentInt int
currentInt, err = strconv.Atoi(p)
if err != nil {
return nil, err
}
if currentInt == 0 && !allowZero {
return nil, fmt.Errorf("zero is not valid")
}
if currentInt < min {
return nil, fmt.Errorf("%d is below minimum %d", currentInt, min)
}
if currentInt > max {
return nil, fmt.Errorf("%d is above maximum %d", currentInt, max)
}
ints[i] = currentInt
}
return ints, nil
}
func parseQualifiedWeekdays(str string) ([]QualifiedWeekday, error) {
var err error
parts := strings.Split(str, ",")
wds := make([]QualifiedWeekday, len(parts))
for i, p := range parts {
if len(p) == 0 {
return nil, errors.New("cannot have empty weekday segment in a comma-separated list")
}
idx := 0
switch p[0] {
case '-', '+':
idx++
}
for _, r := range p[idx:] {
if !unicode.IsDigit(r) {
break
}
idx += utf8.RuneLen(r)
}
var digit int
if idx > 0 {
digit, err = strconv.Atoi(p[:idx])
if err != nil {
return nil, err
}
}
wd, err := parseWeekday(p[idx:])
if err != nil {
return nil, err
}
wds[i] = QualifiedWeekday{N: digit, WD: wd}
}
return wds, nil
}
func parseWeekday(str string) (time.Weekday, error) {
switch strings.ToLower(str) {
case "mo":
return time.Monday, nil
case "tu":
return time.Tuesday, nil
case "we":
return time.Wednesday, nil
case "th":
return time.Thursday, nil
case "fr":
return time.Friday, nil
case "sa":
return time.Saturday, nil
case "su":
return time.Sunday, nil
default:
return time.Sunday, fmt.Errorf("invalid day of week %q", str)
}
}
func parseMonths(str string) ([]time.Month, error) {
parts := strings.Split(str, ",")
months := make([]time.Month, len(parts))
for i, p := range parts {
parsedInt, err := strconv.Atoi(p)
if err != nil {
return nil, err
}
months[i] = time.Month(parsedInt)
}
return months, nil
}
func strToFreq(str string) (Frequency, error) {
switch strings.ToLower(str) {
case "secondly":
return Secondly, nil
case "minutely":
return Minutely, nil
case "hourly":
return Hourly, nil
case "daily":
return Daily, nil
case "weekly":
return Weekly, nil
case "monthly":
return Monthly, nil
case "yearly":
return Yearly, nil
default:
return Yearly, fmt.Errorf("frequency %q is not valid", str)
}
}
func parseSkip(str string) (InvalidBehavior, error) {
switch strings.ToLower(str) {
case "omit":
return OmitInvalid, nil
case "backward":
return PrevInvalid, nil
case "forward":
return NextInvalid, nil
}
return OmitInvalid, fmt.Errorf("skip value %v is not valid", str)
}
func parseRScale(str string) error {
switch strings.ToLower(str) {
case "gregorian", "gregory":
return nil
default:
return fmt.Errorf("invalid rscale %q: only gregorian is supported", str)
}
}