Skip to content

Commit

Permalink
templates: use reflection for parseTime
Browse files Browse the repository at this point in the history
  • Loading branch information
Joe committed Nov 26, 2020
1 parent cd317b5 commit bd69534
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions common/templates/general.go
Original file line number Diff line number Diff line change
Expand Up @@ -999,31 +999,35 @@ func tmplParseTime(layouts interface{}, value string, optionalArgs ...string) (t
}

var parsed time.Time
switch l := layouts.(type) {
case []interface{}:
for _, layout := range l {
switch v := layout.(type) {

val := reflect.ValueOf(layouts)
switch val.Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < val.Len(); i++ {
switch layout := val.Index(i).Interface().(type) {
case string:
parsed, err = time.ParseInLocation(v, value, loc)
parsed, err = time.ParseInLocation(layout, value, loc)
if err != nil {
// when an error is returned, it implies the value does not match the layout
// as error recovery is not possible within custom commands, returning the error would be useless
// Error recovery is essentially impossible in CC, so throwing an error on invalid input would be useless
continue
}

return parsed, nil
default:
return time.Time{}, errors.New("can't parse time with non-string layout")
}
}

return time.Time{}, nil
case string:
parsed, err = time.ParseInLocation(l, value, loc)
case reflect.String:
parsed, err = time.ParseInLocation(val.Interface().(string), value, loc)
if err != nil {
return time.Time{}, nil
}

return parsed, nil
default:
return time.Time{}, errors.New("argument provided to parseTime() was neither a string slice nor a string")
return time.Time{}, errors.New("argument passed to parseTime() was neither a string slice nor a string")
}
}

Expand Down

0 comments on commit bd69534

Please sign in to comment.