forked from git-chglog/git-chglog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
114 lines (96 loc) · 2.03 KB
/
utils.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
package chglog
import (
"fmt"
"reflect"
"strings"
"time"
)
func dotGet(target interface{}, prop string) (interface{}, bool) {
path := strings.Split(prop, ".")
if len(path) == 0 {
return nil, false
}
for _, key := range path {
var value reflect.Value
if reflect.TypeOf(target).Kind() == reflect.Ptr {
value = reflect.ValueOf(target).Elem()
} else {
value = reflect.ValueOf(target)
}
field := value.FieldByName(strings.Title(key))
if !field.IsValid() {
return nil, false
}
target = field.Interface()
}
return target, true
}
// TODO: dotSet ...
func assignDynamicValues(target interface{}, attrs []string, values []string) {
rv := reflect.ValueOf(target).Elem()
rt := rv.Type()
for i, field := range attrs {
if f, ok := rt.FieldByName(field); ok {
rv.FieldByIndex(f.Index).SetString(values[i])
}
}
}
func compare(a interface{}, operator string, b interface{}) (bool, error) {
at := reflect.TypeOf(a).String()
bt := reflect.TypeOf(a).String()
if at != bt {
return false, fmt.Errorf("\"%s\" and \"%s\" can not be compared", at, bt)
}
switch at {
case "string":
aa := a.(string)
bb := b.(string)
return compareString(aa, operator, bb), nil
case "int":
aa := a.(int)
bb := b.(int)
return compareInt(aa, operator, bb), nil
case "time.Time":
aa := a.(time.Time)
bb := b.(time.Time)
return compareTime(aa, operator, bb), nil
}
return false, nil
}
func compareString(a string, operator string, b string) bool {
switch operator {
case "<":
return a < b
case ">":
return a > b
default:
return false
}
}
func compareInt(a int, operator string, b int) bool {
switch operator {
case "<":
return a < b
case ">":
return a > b
default:
return false
}
}
func compareTime(a time.Time, operator string, b time.Time) bool {
switch operator {
case "<":
return !a.After(b)
case ">":
return a.After(b)
default:
return false
}
}
func convNewline(str, nlcode string) string {
return strings.NewReplacer(
"\r\n", nlcode,
"\r", nlcode,
"\n", nlcode,
).Replace(str)
}