github.com/git-chglog/git-chglog@v0.15.5-0.20240126074033-6a6993d52d69/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 //nolint:staticcheck 27 field := value.FieldByName(strings.Title(key)) 28 if !field.IsValid() { 29 return nil, false 30 } 31 32 target = field.Interface() 33 } 34 35 return target, true 36 } 37 38 // TODO: dotSet ... 39 40 func assignDynamicValues(target interface{}, attrs []string, values []string) { 41 rv := reflect.ValueOf(target).Elem() 42 rt := rv.Type() 43 44 for i, field := range attrs { 45 if f, ok := rt.FieldByName(field); ok { 46 rv.FieldByIndex(f.Index).SetString(values[i]) 47 } 48 } 49 } 50 51 func compare(a interface{}, operator string, b interface{}) (bool, error) { 52 at := reflect.TypeOf(a).String() 53 bt := reflect.TypeOf(a).String() 54 if at != bt { 55 return false, fmt.Errorf("\"%s\" and \"%s\" can not be compared", at, bt) 56 } 57 58 switch at { 59 case "string": 60 aa := a.(string) 61 bb := b.(string) 62 return compareString(aa, operator, bb), nil 63 case "int": 64 aa := a.(int) 65 bb := b.(int) 66 return compareInt(aa, operator, bb), nil 67 case "time.Time": 68 aa := a.(time.Time) 69 bb := b.(time.Time) 70 return compareTime(aa, operator, bb), nil 71 } 72 73 return false, nil 74 } 75 76 func compareString(a string, operator string, b string) bool { 77 switch operator { 78 case "<": 79 return a < b 80 case ">": 81 return a > b 82 default: 83 return false 84 } 85 } 86 87 func compareInt(a int, operator string, b int) bool { 88 switch operator { 89 case "<": 90 return a < b 91 case ">": 92 return a > b 93 default: 94 return false 95 } 96 } 97 98 func compareTime(a time.Time, operator string, b time.Time) bool { 99 switch operator { 100 case "<": 101 return !a.After(b) 102 case ">": 103 return a.After(b) 104 default: 105 return false 106 } 107 } 108 109 func convNewline(str, nlcode string) string { 110 return strings.NewReplacer( 111 "\r\n", nlcode, 112 "\r", nlcode, 113 "\n", nlcode, 114 ).Replace(str) 115 }