Skip to content
This repository has been archived by the owner on Oct 17, 2018. It is now read-only.

Commit

Permalink
Extract ParseType function to be reused (#116)
Browse files Browse the repository at this point in the history
  • Loading branch information
cw9 committed Nov 20, 2017
1 parent 1cb339d commit 29ec093
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
38 changes: 29 additions & 9 deletions metric/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,20 +56,40 @@ func (t Type) String() string {
}
}

// ParseType parses a type string and returns the type.
func ParseType(typeStr string) (Type, error) {
validTypeStrs := make([]string, 0, len(validTypes))
for _, valid := range validTypes {
if typeStr == valid.String() {
return valid, nil
}
validTypeStrs = append(validTypeStrs, valid.String())
}
return UnknownType, fmt.Errorf("invalid metric type '%s', valid types are: %s",
typeStr, strings.Join(validTypeStrs, ", "))
}

// MustParseType parses a type string and panics if the input in invalid.
func MustParseType(typeStr string) Type {
t, err := ParseType(typeStr)
if err != nil {
panic(err.Error())
}
return t
}

// UnmarshalYAML unmarshals YAML object into a metric type.
func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {
var str string
if err := unmarshal(&str); err != nil {
return err
}
validTypeStrs := make([]string, 0, len(validTypes))
for _, valid := range validTypes {
if str == valid.String() {
*t = valid
return nil
}
validTypeStrs = append(validTypeStrs, valid.String())

mt, err := ParseType(str)
if err != nil {
return err
}
return fmt.Errorf("invalid metric type '%s' valid types are: %s",
str, strings.Join(validTypeStrs, ", "))

*t = mt
return nil
}
7 changes: 6 additions & 1 deletion metric/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ func TestTypeUnmarshalYAMLErrors(t *testing.T) {
var typ Type
err := yaml.Unmarshal([]byte(input), &typ)
require.Error(t, err)
require.Equal(t, "invalid metric type '"+input+"' valid types are: counter, timer, gauge", err.Error())
require.Equal(t, "invalid metric type '"+input+"', valid types are: counter, timer, gauge", err.Error())
}
}

func TestMustParseType(t *testing.T) {
require.Equal(t, CounterType, MustParseType("counter"))
require.Panics(t, func() { MustParseType("foo") })
}

0 comments on commit 29ec093

Please sign in to comment.