pax_global_header00006660000000000000000000000064135303105670014515gustar00rootroot0000000000000052 comment=c56b1b276ed9b574438218d399184c8863406938 golang-github-mcuadros-go-lookup-0.0~git20171110.5650f26/000077500000000000000000000000001353031056700222635ustar00rootroot00000000000000golang-github-mcuadros-go-lookup-0.0~git20171110.5650f26/.travis.yml000066400000000000000000000001511353031056700243710ustar00rootroot00000000000000language: go go: - 1.2 - 1.3 - 1.4 - tip script: - go get gopkg.in/check.v1 - go test -v . golang-github-mcuadros-go-lookup-0.0~git20171110.5650f26/LICENSE000066400000000000000000000020731353031056700232720ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015 Máximo Cuadros Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. golang-github-mcuadros-go-lookup-0.0~git20171110.5650f26/README.md000066400000000000000000000023511353031056700235430ustar00rootroot00000000000000go-lookup [![Build Status](https://travis-ci.org/mcuadros/go-lookup.png?branch=master)](https://travis-ci.org/mcuadros/go-lookup) [![GoDoc](http://godoc.org/github.com/mcuadros/go-lookup?status.png)](http://godoc.org/github.com/mcuadros/go-lookup) ============================== Small library on top of reflect for make lookups to Structs or Maps. Using a very simple DSL you can access to any property, key or value of any value of Go. Installation ------------ The recommended way to install go-lookup ``` go get github.com/mcuadros/go-lookup ``` Example ------- ```go type Cast struct { Actor, Role string } type Serie struct { Cast []Cast } series := map[string]Serie{ "A-Team": {Cast: []Cast{ {Actor: "George Peppard", Role: "Hannibal"}, {Actor: "Dwight Schultz", Role: "Murdock"}, {Actor: "Mr. T", Role: "Baracus"}, {Actor: "Dirk Benedict", Role: "Faceman"}, }}, } q := "A-Team.Cast.Role" value, _ := LookupString(series, q) fmt.Println(q, "->", value.Interface()) // A-Team.Cast.Role -> [Hannibal Murdock Baracus Faceman] q = "A-Team.Cast[0].Actor" value, _ = LookupString(series, q) fmt.Println(q, "->", value.Interface()) // A-Team.Cast[0].Actor -> George Peppard ``` License ------- MIT, see [LICENSE](LICENSE) golang-github-mcuadros-go-lookup-0.0~git20171110.5650f26/lookup.go000066400000000000000000000122271353031056700241270ustar00rootroot00000000000000/* Small library on top of reflect for make lookups to Structs or Maps. Using a very simple DSL you can access to any property, key or value of any value of Go. */ package lookup import ( "errors" "reflect" "strconv" "strings" ) const ( SplitToken = "." IndexCloseChar = "]" IndexOpenChar = "[" ) var ( ErrMalformedIndex = errors.New("Malformed index key") ErrInvalidIndexUsage = errors.New("Invalid index key usage") ErrKeyNotFound = errors.New("Unable to find the key") ) // LookupString performs a lookup into a value, using a string. Same as `Loookup` // but using a string with the keys separated by `.` func LookupString(i interface{}, path string) (reflect.Value, error) { return Lookup(i, strings.Split(path, SplitToken)...) } // Lookup performs a lookup into a value, using a path of keys. The key should // match with a Field or a MapIndex. For slice you can use the syntax key[index] // to access a specific index. If one key owns to a slice and an index is not // specificied the rest of the path will be apllied to evaley value of the // slice, and the value will be merged into a slice. func Lookup(i interface{}, path ...string) (reflect.Value, error) { value := reflect.ValueOf(i) var parent reflect.Value var err error for i, part := range path { parent = value value, err = getValueByName(value, part) if err == nil { continue } if !isAggregable(parent) { break } value, err = aggreateAggregableValue(parent, path[i:]) break } return value, err } func getValueByName(v reflect.Value, key string) (reflect.Value, error) { var value reflect.Value var index int var err error key, index, err = parseIndex(key) if err != nil { return value, err } switch v.Kind() { case reflect.Ptr, reflect.Interface: return getValueByName(v.Elem(), key) case reflect.Struct: value = v.FieldByName(key) case reflect.Map: kValue := reflect.Indirect(reflect.New(v.Type().Key())) kValue.SetString(key) value = v.MapIndex(kValue) } if !value.IsValid() { return reflect.Value{}, ErrKeyNotFound } if index != -1 { if value.Type().Kind() != reflect.Slice { return reflect.Value{}, ErrInvalidIndexUsage } value = value.Index(index) } if value.Kind() == reflect.Ptr || value.Kind() == reflect.Interface { value = value.Elem() } return value, nil } func aggreateAggregableValue(v reflect.Value, path []string) (reflect.Value, error) { values := make([]reflect.Value, 0) l := v.Len() if l == 0 { ty, ok := lookupType(v.Type(), path...) if !ok { return reflect.Value{}, ErrKeyNotFound } return reflect.MakeSlice(reflect.SliceOf(ty), 0, 0), nil } index := indexFunction(v) for i := 0; i < l; i++ { value, err := Lookup(index(i).Interface(), path...) if err != nil { return reflect.Value{}, err } values = append(values, value) } return mergeValue(values), nil } func indexFunction(v reflect.Value) func(i int) reflect.Value { switch v.Kind() { case reflect.Slice: return v.Index case reflect.Map: keys := v.MapKeys() return func(i int) reflect.Value { return v.MapIndex(keys[i]) } default: panic("unsuported kind for index") } } func mergeValue(values []reflect.Value) reflect.Value { values = removeZeroValues(values) l := len(values) if l == 0 { return reflect.Value{} } sample := values[0] mergeable := isMergeable(sample) t := sample.Type() if mergeable { t = t.Elem() } value := reflect.MakeSlice(reflect.SliceOf(t), 0, 0) for i := 0; i < l; i++ { if !values[i].IsValid() { continue } if mergeable { value = reflect.AppendSlice(value, values[i]) } else { value = reflect.Append(value, values[i]) } } return value } func removeZeroValues(values []reflect.Value) []reflect.Value { l := len(values) var v []reflect.Value for i := 0; i < l; i++ { if values[i].IsValid() { v = append(v, values[i]) } } return v } func isAggregable(v reflect.Value) bool { k := v.Kind() return k == reflect.Map || k == reflect.Slice } func isMergeable(v reflect.Value) bool { k := v.Kind() return k == reflect.Map || k == reflect.Slice } func hasIndex(s string) bool { return strings.Index(s, IndexOpenChar) != -1 } func parseIndex(s string) (string, int, error) { start := strings.Index(s, IndexOpenChar) end := strings.Index(s, IndexCloseChar) if start == -1 && end == -1 { return s, -1, nil } if (start != -1 && end == -1) || (start == -1 && end != -1) { return "", -1, ErrMalformedIndex } index, err := strconv.Atoi(s[start+1 : end]) if err != nil { return "", -1, ErrMalformedIndex } return s[:start], index, nil } func lookupType(ty reflect.Type, path ...string) (reflect.Type, bool) { if len(path) == 0 { return ty, true } switch ty.Kind() { case reflect.Slice, reflect.Array, reflect.Map: if hasIndex(path[0]) { return lookupType(ty.Elem(), path[1:]...) } // Aggregate. return lookupType(ty.Elem(), path...) case reflect.Ptr: return lookupType(ty.Elem(), path...) case reflect.Interface: // We can't know from here without a value. Let's just return this type. return ty, true case reflect.Struct: f, ok := ty.FieldByName(path[0]) if ok { return lookupType(f.Type, path[1:]...) } } return nil, false } golang-github-mcuadros-go-lookup-0.0~git20171110.5650f26/lookup_test.go000066400000000000000000000137311353031056700251670ustar00rootroot00000000000000package lookup import ( "fmt" "reflect" "testing" . "gopkg.in/check.v1" ) // Hook up gocheck into the "go test" runner. func Test(t *testing.T) { TestingT(t) } type S struct{} var _ = Suite(&S{}) func (s *S) TestLookup_Map(c *C) { value, err := Lookup(map[string]int{"foo": 42}, "foo") c.Assert(err, IsNil) c.Assert(value.Int(), Equals, int64(42)) } func (s *S) TestLookup_Ptr(c *C) { value, err := Lookup(&structFixture, "String") c.Assert(err, IsNil) c.Assert(value.String(), Equals, "foo") } func (s *S) TestLookup_Interface(c *C) { value, err := Lookup(structFixture, "Interface") c.Assert(err, IsNil) c.Assert(value.String(), Equals, "foo") } func (s *S) TestLookup_StructBasic(c *C) { value, err := Lookup(structFixture, "String") c.Assert(err, IsNil) c.Assert(value.String(), Equals, "foo") } func (s *S) TestLookup_StructPlusMap(c *C) { value, err := Lookup(structFixture, "Map", "foo") c.Assert(err, IsNil) c.Assert(value.Int(), Equals, int64(42)) } func (s *S) TestLookup_MapNamed(c *C) { value, err := Lookup(mapFixtureNamed, "foo") c.Assert(err, IsNil) c.Assert(value.Int(), Equals, int64(42)) } func (s *S) TestLookup_NotFound(c *C) { _, err := Lookup(structFixture, "qux") c.Assert(err, Equals, ErrKeyNotFound) _, err = Lookup(mapFixture, "qux") c.Assert(err, Equals, ErrKeyNotFound) } func (s *S) TestAggregableLookup_StructIndex(c *C) { value, err := Lookup(structFixture, "StructSlice", "Map", "foo") c.Assert(err, IsNil) c.Assert(value.Interface(), DeepEquals, []int{42, 42}) } func (s *S) TestAggregableLookup_StructNestedMap(c *C) { value, err := Lookup(structFixture, "StructSlice[0]", "String") c.Assert(err, IsNil) c.Assert(value.Interface(), DeepEquals, "foo") } func (s *S) TestAggregableLookup_StructNested(c *C) { value, err := Lookup(structFixture, "StructSlice", "StructSlice", "String") c.Assert(err, IsNil) c.Assert(value.Interface(), DeepEquals, []string{"bar", "foo", "qux", "baz"}) } func (s *S) TestAggregableLookupString_Complex(c *C) { value, err := LookupString(structFixture, "StructSlice.StructSlice[0].String") c.Assert(err, IsNil) c.Assert(value.Interface(), DeepEquals, []string{"bar", "foo", "qux", "baz"}) value, err = LookupString(structFixture, "StructSlice[0].Map.foo") c.Assert(err, IsNil) c.Assert(value.Interface(), DeepEquals, 42) value, err = LookupString(mapComplexFixture, "map.bar") c.Assert(err, IsNil) c.Assert(value.Interface(), DeepEquals, 1) value, err = LookupString(mapComplexFixture, "list.baz") c.Assert(err, IsNil) c.Assert(value.Interface(), DeepEquals, []int{1, 2, 3}) } func (s *S) TestAggregableLookup_EmptySlice(c *C) { fixture := [][]MyStruct{{}} value, err := LookupString(fixture, "String") c.Assert(err, IsNil) c.Assert(value.Interface().([]string), DeepEquals, []string{}) } func (s *S) TestAggregableLookup_EmptyMap(c *C) { fixture := map[string]*MyStruct{} value, err := LookupString(fixture, "Map") c.Assert(err, IsNil) c.Assert(value.Interface().([]map[string]int), DeepEquals, []map[string]int{}) } func (s *S) TestMergeValue(c *C) { v := mergeValue([]reflect.Value{reflect.ValueOf("qux"), reflect.ValueOf("foo")}) c.Assert(v.Interface(), DeepEquals, []string{"qux", "foo"}) } func (s *S) TestMergeValueSlice(c *C) { v := mergeValue([]reflect.Value{ reflect.ValueOf([]string{"foo", "bar"}), reflect.ValueOf([]string{"qux", "baz"}), }) c.Assert(v.Interface(), DeepEquals, []string{"foo", "bar", "qux", "baz"}) } func (s *S) TestMergeValueZero(c *C) { v := mergeValue([]reflect.Value{reflect.Value{}, reflect.ValueOf("foo")}) c.Assert(v.Interface(), DeepEquals, []string{"foo"}) } func (s *S) TestParseIndex(c *C) { key, index, err := parseIndex("foo[42]") c.Assert(err, IsNil) c.Assert(key, Equals, "foo") c.Assert(index, Equals, 42) } func (s *S) TestParseIndexNooIndex(c *C) { key, index, err := parseIndex("foo") c.Assert(err, IsNil) c.Assert(key, Equals, "foo") c.Assert(index, Equals, -1) } func (s *S) TestParseIndexMalFormed(c *C) { key, index, err := parseIndex("foo[]") c.Assert(err, Equals, ErrMalformedIndex) c.Assert(key, Equals, "") c.Assert(index, Equals, -1) key, index, err = parseIndex("foo[42") c.Assert(err, Equals, ErrMalformedIndex) c.Assert(key, Equals, "") c.Assert(index, Equals, -1) key, index, err = parseIndex("foo42]") c.Assert(err, Equals, ErrMalformedIndex) c.Assert(key, Equals, "") c.Assert(index, Equals, -1) } func ExampleLookupString() { type Cast struct { Actor, Role string } type Serie struct { Cast []Cast } series := map[string]Serie{ "A-Team": {Cast: []Cast{ {Actor: "George Peppard", Role: "Hannibal"}, {Actor: "Dwight Schultz", Role: "Murdock"}, {Actor: "Mr. T", Role: "Baracus"}, {Actor: "Dirk Benedict", Role: "Faceman"}, }}, } q := "A-Team.Cast.Role" value, _ := LookupString(series, q) fmt.Println(q, "->", value.Interface()) q = "A-Team.Cast[0].Actor" value, _ = LookupString(series, q) fmt.Println(q, "->", value.Interface()) // Output: // A-Team.Cast.Role -> [Hannibal Murdock Baracus Faceman] // A-Team.Cast[0].Actor -> George Peppard } func ExampleLookup() { type ExampleStruct struct { Values struct { Foo int } } i := ExampleStruct{} i.Values.Foo = 10 value, _ := Lookup(i, "Values", "Foo") fmt.Println(value.Interface()) // Output: 10 } type MyStruct struct { String string Map map[string]int Nested *MyStruct StructSlice []*MyStruct Interface interface{} } type MyKey string var mapFixtureNamed = map[MyKey]int{"foo": 42} var mapFixture = map[string]int{"foo": 42} var structFixture = MyStruct{ String: "foo", Map: mapFixture, Interface: "foo", StructSlice: []*MyStruct{ {Map: mapFixture, String: "foo", StructSlice: []*MyStruct{{String: "bar"}, {String: "foo"}}}, {Map: mapFixture, String: "qux", StructSlice: []*MyStruct{{String: "qux"}, {String: "baz"}}}, }, } var mapComplexFixture = map[string]interface{}{ "map": map[string]interface{}{ "bar": 1, }, "list": []map[string]interface{}{ {"baz": 1}, {"baz": 2}, {"baz": 3}, }, }