forked from ghetzel/pivot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatters.go
287 lines (236 loc) · 6.88 KB
/
formatters.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
package dal
import (
"encoding/base32"
"encoding/base64"
"encoding/hex"
"fmt"
"regexp"
"strings"
"time"
"github.com/ghetzel/go-stockutil/sliceutil"
"github.com/ghetzel/go-stockutil/stringutil"
"github.com/ghetzel/go-stockutil/typeutil"
"github.com/jbenet/go-base58"
)
type EncoderFunc func([]byte) (string, error) //{}
var Base32Encoder = func(src []byte) (string, error) {
return strings.TrimSuffix(base32.StdEncoding.EncodeToString(src), `=`), nil
}
var Base58Encoder = func(src []byte) (string, error) {
return base58.Encode(src), nil
}
var Base64Encoder = func(src []byte) (string, error) {
return strings.TrimSuffix(base64.StdEncoding.EncodeToString(src), `=`), nil
}
var HexEncoder = func(src []byte) (string, error) {
return hex.EncodeToString(src), nil
}
func FormatterFromMap(in map[string]interface{}) (FieldFormatterFunc, error) {
formatters := make([]FieldFormatterFunc, 0)
for name, defn := range in {
if formatter, err := GetFormatter(name, defn); err == nil {
formatters = append(formatters, formatter)
} else {
return nil, fmt.Errorf("Invalid formatter configuration %v: %v", name, err)
}
}
return FormatAll(formatters...), nil
}
func GetFormatter(name string, args interface{}) (FieldFormatterFunc, error) {
switch name {
case `uuid`:
return GenerateUUID, nil
case `encoded-uuid`:
var encoder EncoderFunc
switch fmt.Sprintf("%v", args) {
case `base32`:
encoder = Base32Encoder
case `base58`:
encoder = Base58Encoder
case `base64`:
encoder = Base64Encoder
default:
encoder = HexEncoder
}
return GenerateEncodedUUID(encoder), nil
case `trim-space`:
return TrimSpace, nil
case `change-case`:
return ChangeCase(sliceutil.Stringify(args)...), nil
case `replace`:
return Replace(sliceutil.Sliceify(args)), nil
// case `fields`:
// if typeutil.IsMap(args) {
// return DeriveFromFields()
// }
case `current-time`:
return CurrentTime, nil
case `current-time-if-unset`:
return CurrentTimeIfUnset, nil
case `now-plus-duration`:
return NowPlusDuration(typeutil.V(args).Duration()), nil
default:
return nil, fmt.Errorf("Unknown formatter %q", name)
}
}
func FormatAll(formatters ...FieldFormatterFunc) FieldFormatterFunc {
return func(value interface{}, op FieldOperation) (interface{}, error) {
for _, formatter := range formatters {
if v, err := formatter(value, op); err == nil {
value = v
} else {
return nil, err
}
}
return value, nil
}
}
func ChangeCase(cases ...string) FieldFormatterFunc {
return func(value interface{}, _ FieldOperation) (interface{}, error) {
if record, ok := value.(*Record); ok {
value = record.ID
}
if vStr, err := stringutil.ToString(value); err == nil {
for _, c := range cases {
switch c {
case `upper`:
vStr = strings.ToUpper(vStr)
case `lower`:
vStr = strings.ToLower(vStr)
case `camelize`:
vStr = stringutil.Camelize(vStr)
case `hyphenate`:
vStr = stringutil.Hyphenate(vStr)
case `underscore`:
vStr = stringutil.Underscore(vStr)
case `title`:
vStr = strings.Title(vStr)
default:
return nil, fmt.Errorf("Unsupported case '%s'", c)
}
}
return vStr, nil
} else {
return value, err
}
}
}
func Replace(pairs []interface{}) FieldFormatterFunc {
return func(value interface{}, _ FieldOperation) (interface{}, error) {
if vStr, err := stringutil.ToString(value); err == nil {
for _, pair := range pairs {
p := sliceutil.Stringify(pair)
if len(p) != 2 {
return nil, fmt.Errorf("'replace' formatter requires an argument of [[FINDPATTERN, REPLACEWITH], ..]")
} else {
find := p[0]
replace := p[1]
if record, ok := value.(*Record); ok {
value = record.ID
}
if rx, err := regexp.Compile(find); err == nil {
vStr = rx.ReplaceAllString(vStr, replace)
} else {
return value, fmt.Errorf("invalid find pattern: %v", err)
}
}
}
return vStr, nil
} else {
return value, err
}
}
}
func TrimSpace(value interface{}, _ FieldOperation) (interface{}, error) {
if record, ok := value.(*Record); ok {
value = record.ID
}
if vStr, err := stringutil.ToString(value); err == nil {
return strings.TrimSpace(vStr), nil
} else {
return value, err
}
}
// Generates a V4 UUID value if the existing value is empty.
func GenerateUUID(value interface{}, _ FieldOperation) (interface{}, error) {
if record, ok := value.(*Record); ok {
value = record.ID
}
if typeutil.IsZero(value) {
value = stringutil.UUID().String()
}
return value, nil
}
// Same as GenerateUUID, but allows for a custom representation of the underlying bytes.
func GenerateEncodedUUID(encoder EncoderFunc) FieldFormatterFunc {
return func(value interface{}, _ FieldOperation) (interface{}, error) {
if record, ok := value.(*Record); ok {
value = record.ID
}
if typeutil.IsZero(value) {
if v, err := encoder(stringutil.UUID().Bytes()); err == nil {
if typeutil.IsZero(v) {
return value, fmt.Errorf("UUID encoder produced a zero-length result")
}
value = v
} else {
return value, err
}
}
return value, nil
}
}
// Only evaluates the given formatter if the current value of the field is empty.
func IfUnset(onlyIf FieldFormatterFunc) FieldFormatterFunc {
return func(value interface{}, op FieldOperation) (interface{}, error) {
if onlyIf != nil {
if typeutil.IsZero(value) {
return onlyIf(value, op)
}
}
return value, nil
}
}
// Extracts values from the given Record and generates a deterministic output based on those values.
func DeriveFromFields(format string, fields ...string) FieldFormatterFunc {
return func(input interface{}, _ FieldOperation) (interface{}, error) {
if record, ok := input.(*Record); ok {
values := make([]interface{}, len(fields))
for i, field := range fields {
values[i] = record.Get(field)
}
return fmt.Sprintf(format, values...), nil
} else {
return nil, fmt.Errorf("DeriveFromFields formatter requires a *dal.Record argument, got %T", input)
}
}
}
// Returns the current time every time the field is persisted.
func CurrentTime(value interface{}, op FieldOperation) (interface{}, error) {
if op == PersistOperation {
return time.Now(), nil
} else {
return value, nil
}
}
// Returns the current time when the field is persisted if the current value is empty.
func CurrentTimeIfUnset(value interface{}, op FieldOperation) (interface{}, error) {
return IfUnset(func(v interface{}, o FieldOperation) (interface{}, error) {
if o == PersistOperation {
return time.Now(), nil
} else {
return v, nil
}
})(value, op)
}
// Returns the current time with an added offset when the field is persisted.
func NowPlusDuration(duration time.Duration) FieldFormatterFunc {
return func(value interface{}, op FieldOperation) (interface{}, error) {
if op == PersistOperation {
if duration != 0 {
return time.Now().Add(duration), nil
}
}
return value, nil
}
}