diff --git a/git/odb/object_type.go b/git/odb/object_type.go new file mode 100644 index 00000000..d2834201 --- /dev/null +++ b/git/odb/object_type.go @@ -0,0 +1,45 @@ +package odb + +import "strings" + +// ObjectType is a constant enumeration type for identifying the kind of object +// type an implementing instance of the Object interface is. +type ObjectType uint8 + +const ( + UnknownObjectType ObjectType = iota + BlobObjectType + TreeObjectType + CommitObjectType +) + +// ObjectTypeFromString converts from a given string to an ObjectType +// enumeration instance. +func ObjectTypeFromString(s string) ObjectType { + switch strings.ToLower(s) { + case "blob": + return BlobObjectType + case "tree": + return TreeObjectType + case "commit": + return CommitObjectType + default: + return UnknownObjectType + } +} + +// String implements the fmt.Stringer interface and returns a string +// representation of the ObjectType enumeration instance. +func (t ObjectType) String() string { + switch t { + case UnknownObjectType: + return "unknown" + case BlobObjectType: + return "blob" + case TreeObjectType: + return "tree" + case CommitObjectType: + return "commit" + } + return "" +} diff --git a/git/odb/object_type_test.go b/git/odb/object_type_test.go new file mode 100644 index 00000000..b65f70a4 --- /dev/null +++ b/git/odb/object_type_test.go @@ -0,0 +1,35 @@ +package odb + +import ( + "math" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestObjectTypeFromString(t *testing.T) { + for str, typ := range map[string]ObjectType{ + "blob": BlobObjectType, + "tree": TreeObjectType, + "commit": CommitObjectType, + "something else": UnknownObjectType, + } { + t.Run(str, func(t *testing.T) { + assert.Equal(t, typ, ObjectTypeFromString(str)) + }) + } +} + +func TestObjectTypeToString(t *testing.T) { + for typ, str := range map[ObjectType]string{ + BlobObjectType: "blob", + TreeObjectType: "tree", + CommitObjectType: "commit", + UnknownObjectType: "unknown", + ObjectType(math.MaxUint8): "", + } { + t.Run(str, func(t *testing.T) { + assert.Equal(t, str, typ.String()) + }) + } +}