This repository has been archived by the owner on Feb 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactivity-template.go
202 lines (181 loc) · 4.85 KB
/
activity-template.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/fatih/structtag"
"github.com/strava/go.strava"
"io/ioutil"
"path/filepath"
"reflect"
"regexp"
"strings"
"sync"
"text/template"
"time"
)
type TemplateEngine struct {
templateTypeInfo *ParsedTypeInfo
cache map[string]*template.Template
cacheMutex sync.Mutex
sampleActivity *strava.ActivitySummary
}
type ParsedTypeInfo struct {
Fields map[string]string
StructFields map[string]*ParsedTypeInfo
}
var (
ActivityTypeInfo *ParsedTypeInfo
UserTemplateRegex = regexp.MustCompile("{([^{]*)}")
)
func init() {
ActivityTypeInfo = parseType(reflect.TypeOf(strava.ActivitySummary{}))
}
func parseType(t reflect.Type) *ParsedTypeInfo {
timeType := reflect.TypeOf(time.Time{})
result := &ParsedTypeInfo{Fields: make(map[string]string), StructFields: make(map[string]*ParsedTypeInfo)}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
tags, err := structtag.Parse(string(f.Tag))
if err != nil {
continue
}
jsonTag, err := tags.Get("json")
if err != nil {
continue
}
result.Fields[jsonTag.Name] = f.Name
if f.Type.Kind() == reflect.Struct && f.Type != timeType {
result.StructFields[jsonTag.Name] = parseType(f.Type)
}
}
return result
}
func NewActivityTemplateEngine(appDir string) *TemplateEngine {
var sampleActivity *strava.ActivitySummary
content, err := ioutil.ReadFile(filepath.Join(appDir, "samples", "activity.json"))
if err == nil {
json.Unmarshal(content, &sampleActivity)
}
return &TemplateEngine{
templateTypeInfo: ActivityTypeInfo,
cache: make(map[string]*template.Template),
sampleActivity: sampleActivity,
}
}
func (te *TemplateEngine) Build(userTemplate string) (string, error) {
result := userTemplate
matches := UserTemplateRegex.FindAllStringSubmatch(userTemplate, -1)
for _, match := range matches {
pattern, err := te.convert(match[1])
if err != nil {
return userTemplate, err
}
result = strings.Replace(result, match[0], "{{"+pattern+"}}", 1)
}
return result, nil
}
func (te *TemplateEngine) convert(userPattern string) (string, error) {
var partUnit *Unit
parts := strings.Split(userPattern, ".")
result := userPattern
hasError := false
isPace := false
currentTypeInfo := te.templateTypeInfo
for i, part := range parts {
if name, ok := currentTypeInfo.Fields[part]; ok {
parts[i] = name
if typeInfo, ok := currentTypeInfo.StructFields[part]; ok {
currentTypeInfo = typeInfo
}
} else if i == len(parts)-1 {
isPace = strings.Contains(part, "_pace_") || strings.HasSuffix(part, "_pace")
if isPace {
if strings.Contains(part, "_pace_") {
part = strings.Replace(part, "_pace_", "_speed_", -1)
} else {
part = part[:len(part)-len("_pace")] + "_speed_m"
}
}
sepIndex := strings.LastIndex(part, "_")
if sepIndex >= 0 {
unitStr := part[sepIndex+1:]
unit := GetKnownUnit(unitStr)
if unit != nil {
if name, ok := currentTypeInfo.Fields[part[:sepIndex]]; ok {
parts[i] = name
partUnit = unit
} else {
hasError = true
}
} else {
hasError = true
}
} else {
hasError = true
}
} else {
hasError = true
break
}
}
if hasError {
return userPattern, fmt.Errorf("invalid field {%s}", userPattern)
}
result = "." + strings.Join(parts, ".")
if strings.HasSuffix(result, "Speed") {
partUnitName := "m"
if partUnit != nil {
partUnitName = partUnit.Name
}
funcName := "toSpeed"
if isPace {
funcName = "toPace"
}
result = fmt.Sprintf("%s %s \"%s\"", funcName, result, partUnitName)
} else if partUnit != nil {
result = fmt.Sprintf("toUnit %s \"%s\"", result, partUnit.Name)
} else if strings.HasSuffix(result, "Time") {
result = fmt.Sprintf("toTime %s", result)
}
return result, nil
}
func (te *TemplateEngine) Compile(userTemplate string) (*template.Template, error) {
tmpl := te.getTemplateFromCache(userTemplate)
if tmpl != nil {
return tmpl, nil
}
realTemplate, err := te.Build(userTemplate)
if err != nil {
return nil, err
}
tmpl, err = template.New(userTemplate).Funcs(template.FuncMap{
"toUnit": ConvertToUnit,
"toSpeed": ConvertToSpeed,
"toPace": ConvertToPace,
"toTime": getDurationText,
}).Parse(realTemplate)
if err != nil {
return nil, err
}
te.putTemplateFromCache(userTemplate, tmpl)
return tmpl, nil
}
func (te *TemplateEngine) SampleText(tmpl *template.Template) string {
if te.sampleActivity == nil {
return ""
}
var buf bytes.Buffer
tmpl.Execute(&buf, te.sampleActivity)
return buf.String()
}
func (te *TemplateEngine) getTemplateFromCache(userTemplate string) *template.Template {
te.cacheMutex.Lock()
defer te.cacheMutex.Unlock()
return te.cache[userTemplate]
}
func (te *TemplateEngine) putTemplateFromCache(userTemplate string, tmpl *template.Template) {
te.cacheMutex.Lock()
defer te.cacheMutex.Unlock()
te.cache[userTemplate] = tmpl
}