github.com/BrandonManuel/git-chglog@v0.0.0-20200903004639-7a62fa08787a/utils.go (about) 1 package chglog 2 3 import ( 4 "fmt" 5 "reflect" 6 "strings" 7 "time" 8 ) 9 10 func dotGet(target interface{}, prop string) (interface{}, bool) { 11 path := strings.Split(prop, ".") 12 13 if len(path) == 0 { 14 return nil, false 15 } 16 17 for _, key := range path { 18 var value reflect.Value 19 20 if reflect.TypeOf(target).Kind() == reflect.Ptr { 21 value = reflect.ValueOf(target).Elem() 22 } else { 23 value = reflect.ValueOf(target) 24 } 25 26 field := value.FieldByName(strings.Title(key)) 27 if !field.IsValid() { 28 return nil, false 29 } 30 31 target = field.Interface() 32 } 33 34 return target, true 35 } 36 37 // TODO: dotSet ... 38 39 func assignDynamicValues(target interface{}, attrs []string, values []string) { 40 rv := reflect.ValueOf(target).Elem() 41 rt := rv.Type() 42 43 for i, field := range attrs { 44 if f, ok := rt.FieldByName(field); ok { 45 rv.FieldByIndex(f.Index).SetString(values[i]) 46 } 47 } 48 } 49 50 func compare(a interface{}, operator string, b interface{}) (bool, error) { 51 at := reflect.TypeOf(a).String() 52 bt := reflect.TypeOf(a).String() 53 if at != bt { 54 return false, fmt.Errorf("\"%s\" and \"%s\" can not be compared", at, bt) 55 } 56 57 switch at { 58 case "string": 59 aa := a.(string) 60 bb := b.(string) 61 return compareString(aa, operator, bb), nil 62 case "int": 63 aa := a.(int) 64 bb := b.(int) 65 return compareInt(aa, operator, bb), nil 66 case "time.Time": 67 aa := a.(time.Time) 68 bb := b.(time.Time) 69 return compareTime(aa, operator, bb), nil 70 } 71 72 return false, nil 73 } 74 75 func compareString(a string, operator string, b string) bool { 76 switch operator { 77 case "<": 78 return a < b 79 case ">": 80 return a > b 81 default: 82 return false 83 } 84 } 85 86 func compareInt(a int, operator string, b int) bool { 87 switch operator { 88 case "<": 89 return a < b 90 case ">": 91 return a > b 92 default: 93 return false 94 } 95 } 96 97 func compareTime(a time.Time, operator string, b time.Time) bool { 98 switch operator { 99 case "<": 100 return !a.After(b) 101 case ">": 102 return a.After(b) 103 default: 104 return false 105 } 106 } 107 108 func convNewline(str, nlcode string) string { 109 return strings.NewReplacer( 110 "\r\n", nlcode, 111 "\r", nlcode, 112 "\n", nlcode, 113 ).Replace(str) 114 }