diff --git a/pkg/runtime/helper.go b/pkg/runtime/helper.go index b6e944d98c7..840a9fddcca 100644 --- a/pkg/runtime/helper.go +++ b/pkg/runtime/helper.go @@ -243,3 +243,28 @@ func (metaInsertion) Interpret(in interface{}) (version, kind string) { m := in.(*metaInsertion) return m.JSONBase.APIVersion, m.JSONBase.Kind } + +// Extract list returns obj's Items element as an array of runtime.Objects. +// Returns an error if obj is not a List type (does not have an Items member). +func ExtractList(obj Object) ([]Object, error) { + v := reflect.ValueOf(obj) + if !v.IsValid() { + return nil, fmt.Errorf("nil object") + } + items := v.Elem().FieldByName("Items") + if !items.IsValid() { + return nil, fmt.Errorf("no Items field") + } + if items.Kind() != reflect.Slice { + return nil, fmt.Errorf("Items field is not a slice") + } + list := make([]Object, items.Len()) + for i := range list { + item, ok := items.Index(i).Addr().Interface().(Object) + if !ok { + return nil, fmt.Errorf("item in index %v isn't an object", i) + } + list[i] = item + } + return list, nil +} diff --git a/pkg/runtime/helper_test.go b/pkg/runtime/helper_test.go index 86e368fc58d..b68178a3227 100644 --- a/pkg/runtime/helper_test.go +++ b/pkg/runtime/helper_test.go @@ -57,3 +57,25 @@ func TestBadJSONRejection(t *testing.T) { t.Errorf("Kind is set but doesn't match the object type: %s", badJSONKindMismatch) }*/ } + +func TestExtractList(t *testing.T) { + pl := &api.PodList{ + Items: []api.Pod{ + {JSONBase: api.JSONBase{ID: "1"}}, + {JSONBase: api.JSONBase{ID: "2"}}, + {JSONBase: api.JSONBase{ID: "3"}}, + }, + } + list, err := runtime.ExtractList(pl) + if err != nil { + t.Fatalf("Unexpected error %v", err) + } + if e, a := len(list), len(pl.Items); e != a { + t.Fatalf("Expected %v, got %v", e, a) + } + for i := range list { + if e, a := list[i].(*api.Pod).ID, pl.Items[i].ID; e != a { + t.Fatalf("Expected %v, got %v", e, a) + } + } +}