Skip to content

Commit

Permalink
Merge pull request #641 from cbranch/altsrc-parse-durations
Browse files Browse the repository at this point in the history
altsrc: Parse durations from strings
  • Loading branch information
jszwedko authored Jan 28, 2018
2 parents 1355f91 + d604b6f commit d3ae77c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
24 changes: 14 additions & 10 deletions altsrc/map_input_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,24 +71,28 @@ func (fsm *MapInputSource) Int(name string) (int, error) {
func (fsm *MapInputSource) Duration(name string) (time.Duration, error) {
otherGenericValue, exists := fsm.valueMap[name]
if exists {
otherValue, isType := otherGenericValue.(time.Duration)
if !isType {
return 0, incorrectTypeForFlagError(name, "duration", otherGenericValue)
}
return otherValue, nil
return castDuration(name, otherGenericValue)
}
nestedGenericValue, exists := nestedVal(name, fsm.valueMap)
if exists {
otherValue, isType := nestedGenericValue.(time.Duration)
if !isType {
return 0, incorrectTypeForFlagError(name, "duration", nestedGenericValue)
}
return otherValue, nil
return castDuration(name, nestedGenericValue)
}

return 0, nil
}

func castDuration(name string, value interface{}) (time.Duration, error) {
if otherValue, isType := value.(time.Duration); isType {
return otherValue, nil
}
otherStringValue, isType := value.(string)
parsedValue, err := time.ParseDuration(otherStringValue)
if !isType || err != nil {
return 0, incorrectTypeForFlagError(name, "duration", value)
}
return parsedValue, nil
}

// Float64 returns an float64 from the map if it exists otherwise returns 0
func (fsm *MapInputSource) Float64(name string) (float64, error) {
otherGenericValue, exists := fsm.valueMap[name]
Expand Down
25 changes: 25 additions & 0 deletions altsrc/map_input_source_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package altsrc

import (
"testing"
"time"
)

func TestMapDuration(t *testing.T) {
inputSource := &MapInputSource{
file: "test",
valueMap: map[interface{}]interface{}{
"duration_of_duration_type": time.Minute,
"duration_of_string_type": "1m",
"duration_of_int_type": 1000,
},
}
d, err := inputSource.Duration("duration_of_duration_type")
expect(t, time.Minute, d)
expect(t, nil, err)
d, err = inputSource.Duration("duration_of_string_type")
expect(t, time.Minute, d)
expect(t, nil, err)
d, err = inputSource.Duration("duration_of_int_type")
refute(t, nil, err)
}

0 comments on commit d3ae77c

Please sign in to comment.