-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathparser.go
356 lines (302 loc) · 9.58 KB
/
parser.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
package dateparser
import (
"fmt"
"strings"
"sync"
"time"
"slices"
"github.com/markusmobius/go-dateparser/date"
"github.com/markusmobius/go-dateparser/internal/data"
"github.com/markusmobius/go-dateparser/internal/language"
"github.com/markusmobius/go-dateparser/internal/parser/absolute"
"github.com/markusmobius/go-dateparser/internal/parser/formatted"
"github.com/markusmobius/go-dateparser/internal/parser/nospace"
"github.com/markusmobius/go-dateparser/internal/parser/relative"
"github.com/markusmobius/go-dateparser/internal/parser/timestamp"
"github.com/markusmobius/go-dateparser/internal/setting"
"github.com/markusmobius/go-dateparser/internal/strutil"
"github.com/markusmobius/go-dateparser/internal/timezone"
)
// Parser is object that handles language detection, translation and subsequent
// generic parsing of string representing date and/or time.
type Parser struct {
sync.Mutex
// DetectLanguagesFunction is a function for language detection that takes
// as input a `text` and returns a list of detected language codes. Note:
// this function is only used if `languages` and `locales` are not provided.
DetectLanguagesFunction func(string) []string
// ParserTypes is a list of types of parsers to try, allowing to customize which parsers are tried
// against the input date string, and in which order they are tried. By default it will use
// all parser in following order: `Timestamp`, `RelativeTime`, `CustomFormat`, `AbsoluteTime`,
// and finally `NoSpacesTime`.
ParserTypes []ParserType
usedLocales []*data.LocaleData
usedLocalesTracker strutil.Dict
uniqueCharsets map[string][]rune
}
// ParserType is the variable to specify which type of parser that will be used.
type ParserType uint8
const (
// Timestamp is parser to parse Unix timestamp.
Timestamp ParserType = iota
// NegativeTimestamp is parser to parse Unix timestamp in negative value.
NegativeTimestamp
// RelativeTime is parser to parse date string with relative value like
// "1 year, 2 months ago" and "3 hours, 50 minutes ago".
RelativeTime
// CustomFormat is parser to parse a date string with custom formats.
CustomFormat
// AbsoluteTime is parser to parse date string with absolute value like
// "12 August 2021" and "23 January, 15:10:01".
AbsoluteTime
// NoSpacesTime is parser to parse date string that written without spaces,
// for example 2021-10-11 that written as 20211011.
NoSpacesTime
)
// Parse parses string representing date and/or time in recognizable localized formats.
// Supports parsing multiple languages.
func (p *Parser) Parse(cfg *Configuration, str string, formats ...string) (date.Date, error) {
// Lock mutex
p.Lock()
defer p.Unlock()
// Validate and initiate parsers
for _, parser := range p.ParserTypes {
if parser > NoSpacesTime {
return date.Date{}, fmt.Errorf("invalid parser type: %d", parser)
}
}
if len(p.ParserTypes) == 0 {
p.ParserTypes = []ParserType{
Timestamp,
NegativeTimestamp,
RelativeTime,
CustomFormat,
AbsoluteTime,
NoSpacesTime,
}
}
// Initiate and validate config
if cfg == nil {
cfg = &Configuration{}
}
cfg = cfg.initiate()
err := cfg.validate()
if err != nil {
return date.Date{}, fmt.Errorf("config error: %w", err)
}
// Convert config to internal config
iCfg := cfg.toInternalConfig()
// Try to parse with specified formats
var dt date.Date
if dt = formatted.Parse(iCfg, str, formats...); !dt.IsZero() {
return dt, nil
}
// Sanitize string
originalStr := str
str = strutil.SanitizeDate(str)
// Find the suitable locales for this string
locales, err := p.getApplicableLocales(cfg, iCfg, str)
if err != nil {
return date.Date{}, err
}
// Process each locale
for _, locale := range locales {
// Create date order for this locale
dateOrder := locale.DateOrder
if cfg.DateOrder != nil {
do := cfg.DateOrder(locale.Name)
if do, valid := validateDateOrder(do); valid {
dateOrder = do
}
}
// Create locale specific config
lCfg := iCfg.Clone()
lCfg.DateOrder = dateOrder
// Translate string
translations := language.Translate(lCfg, locale, str, false)
translationsWithFormat := language.Translate(lCfg, locale, str, true)
for _, parserType := range p.ParserTypes {
switch parserType {
case Timestamp:
dt = timestamp.Parse(lCfg, str, false)
case NegativeTimestamp:
dt = timestamp.Parse(lCfg, str, true)
case RelativeTime:
dt = p.tryRelativeTime(lCfg, translations)
case CustomFormat:
dt = p.tryCustomFormat(lCfg, translationsWithFormat, formats...)
case AbsoluteTime:
dt = p.tryAbsoluteTime(lCfg, translations)
case NoSpacesTime:
dt = p.tryNoSpacesTime(lCfg, translations)
}
if !dt.IsZero() {
if cfg.TryPreviousLocales {
p.saveUsedLocale(locale)
}
dt.Locale = locale.Name
return dt, nil
}
}
}
return date.Date{}, fmt.Errorf("failed to parse \"%s\": unknown format", originalStr)
}
func (p *Parser) tryRelativeTime(iCfg *setting.Configuration, translations []string) date.Date {
for _, translation := range translations {
dt := relative.Parse(iCfg, translation)
if !dt.IsZero() {
return dt
}
}
return date.Date{}
}
func (p *Parser) tryCustomFormat(iCfg *setting.Configuration, translations []string, formats ...string) date.Date {
for _, translation := range translations {
dt := formatted.Parse(iCfg, translation, formats...)
if !dt.IsZero() {
return dt
}
}
return date.Date{}
}
func (p *Parser) tryAbsoluteTime(iCfg *setting.Configuration, translations []string) date.Date {
for _, translation := range translations {
if t, tz := p.stripBracesAndTimezones(translation); t != "" {
dt, _ := absolute.Parse(iCfg, t, tz)
dt = p.applyTimezone(iCfg, dt, tz)
if !dt.IsZero() {
return dt
}
}
}
return date.Date{}
}
func (p *Parser) tryNoSpacesTime(iCfg *setting.Configuration, translations []string) date.Date {
for _, translation := range translations {
if t, tz := p.stripBracesAndTimezones(translation); t != "" {
dt, _ := nospace.Parse(iCfg, t)
dt = p.applyTimezone(iCfg, dt, tz)
if !dt.IsZero() {
return dt
}
}
}
return date.Date{}
}
func (p *Parser) getApplicableLocales(cfg *Configuration, iCfg *setting.Configuration, str string) ([]*data.LocaleData, error) {
// Prepare results
var results []*data.LocaleData
resultTracker := strutil.NewDict()
// Normalize and prepare date strings
str = strutil.NormalizeString(str)
dateStrings := []string{str}
if poppedTz, _ := timezone.PopTzOffset(str); poppedTz != str {
dateStrings = append(dateStrings, poppedTz)
}
// Fetch previously used locales first
if cfg.TryPreviousLocales {
ld := p.checkPreviousLocales(iCfg, dateStrings)
if ld != nil {
results = append(results, ld)
resultTracker.Add(ld.Name)
}
}
// If specified, use external detector to fetch languages
languages := slices.Clone(cfg.Languages)
if p.DetectLanguagesFunction != nil && len(cfg.Locales) == 0 && len(languages) == 0 {
detectionResults := p.DetectLanguagesFunction(str)
languages = append(languages, detectionResults...)
}
// Load locales
locales, err := language.GetLocales(cfg.Locales, languages, cfg.Region, cfg.UseGivenOrder, false)
if err != nil && err != language.ErrNotFound {
return nil, err
}
for _, locale := range locales {
if resultTracker.Contain(locale.Name) {
continue
}
// Check if locale is applicable
var isApplicable bool
for _, ds := range dateStrings {
if p.localeIsApplicable(iCfg, locale, ds) {
isApplicable = true
break
}
}
if isApplicable {
results = append(results, locale)
resultTracker.Add(locale.Name)
}
}
// Finally, append locales of default languages
if len(iCfg.DefaultLanguages) > 0 {
locales, _ := language.GetLocales(nil, cfg.DefaultLanguages, cfg.Region, cfg.UseGivenOrder, false)
for _, locale := range locales {
if !resultTracker.Contain(locale.Name) {
results = append(results, locale)
}
}
}
return results, nil
}
func (p *Parser) checkPreviousLocales(iCfg *setting.Configuration, dateStrings []string) *data.LocaleData {
for _, usedLocale := range p.usedLocales {
for _, ds := range dateStrings {
if p.localeIsApplicable(iCfg, usedLocale, ds) {
return usedLocale
}
}
}
return nil
}
func (p *Parser) saveUsedLocale(ld *data.LocaleData) {
if p.usedLocalesTracker == nil {
p.usedLocalesTracker = strutil.NewDict()
}
if !p.usedLocalesTracker.Contain(ld.Name) {
p.usedLocalesTracker.Add(ld.Name)
p.usedLocales = append(p.usedLocales, ld)
}
}
func (p *Parser) localeIsApplicable(iCfg *setting.Configuration, ld *data.LocaleData, s string) bool {
return language.IsApplicable(iCfg, ld, s, false)
}
func (p *Parser) stripBracesAndTimezones(s string) (string, timezone.OffsetData) {
s = strutil.StripBraces(s)
return timezone.PopTzOffset(s)
}
func (p *Parser) applyTimezone(iCfg *setting.Configuration, dt date.Date, tz timezone.OffsetData) date.Date {
if dt.IsZero() || (tz.IsZero() && iCfg.DefaultTimezone == nil) {
return dt
}
var tzName string
var tzOffset int
if !tz.IsZero() {
tzName, tzOffset = tz.Name, tz.Offset
} else {
tzName, tzOffset = dt.Time.In(iCfg.DefaultTimezone).Zone()
}
dt.Time = time.Date(dt.Time.Year(), dt.Time.Month(), dt.Time.Day(),
dt.Time.Hour(), dt.Time.Minute(), dt.Time.Second(), dt.Time.Nanosecond(),
time.FixedZone(tzName, tzOffset))
return dt
}
func validateDateOrder(do string) (string, bool) {
if len(do) != 3 {
return do, false
}
do = strings.ToUpper(do)
mapChars := map[rune]struct{}{}
for _, r := range do {
if r == 'D' || r == 'M' || r == 'Y' {
mapChars[r] = struct{}{}
} else {
return do, false
}
}
if len(mapChars) != 3 {
return do, false
}
return do, true
}