Fix sorting from 2 bugs

This commit is contained in:
Brendan Burns
2015-10-19 22:44:48 -07:00
parent b02b5b9f87
commit 2935075388
3 changed files with 155 additions and 21 deletions

View File

@@ -23,6 +23,7 @@ import (
"sort"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/v1"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/util/jsonpath"
@@ -60,8 +61,35 @@ func (s *SortingPrinter) sortObj(obj runtime.Object) error {
if len(objs) == 0 {
return nil
}
sorter, err := SortObjects(objs, s.SortField)
if err != nil {
return err
}
switch list := obj.(type) {
case *v1.List:
outputList := make([]runtime.RawExtension, len(objs))
for ix := range objs {
outputList[ix] = list.Items[sorter.OriginalPosition(ix)]
}
list.Items = outputList
return nil
}
return runtime.SetList(obj, objs)
}
func SortObjects(objs []runtime.Object, fieldInput string) (*RuntimeSort, error) {
parser := jsonpath.New("sorting")
parser.Parse(s.SortField)
field, err := massageJSONPath(fieldInput)
if err != nil {
return nil, err
}
if err := parser.Parse(field); err != nil {
return nil, err
}
for ix := range objs {
item := objs[ix]
@@ -69,31 +97,38 @@ func (s *SortingPrinter) sortObj(obj runtime.Object) error {
case *runtime.Unknown:
var err error
if objs[ix], err = api.Codec.Decode(u.RawJSON); err != nil {
return err
return nil, err
}
}
}
values, err := parser.FindResults(reflect.ValueOf(objs[0]).Elem().Interface())
if err != nil {
return err
return nil, err
}
if len(values) == 0 {
return fmt.Errorf("couldn't find any field with path: %s", s.SortField)
}
sorter := &RuntimeSort{
field: s.SortField,
objs: objs,
return nil, fmt.Errorf("couldn't find any field with path: %s", field)
}
sorter := NewRuntimeSort(field, objs)
sort.Sort(sorter)
runtime.SetList(obj, sorter.objs)
return nil
return sorter, nil
}
// RuntimeSort is an implementation of the golang sort interface that knows how to sort
// lists of runtime.Object
type RuntimeSort struct {
field string
objs []runtime.Object
field string
objs []runtime.Object
origPosition []int
}
func NewRuntimeSort(field string, objs []runtime.Object) *RuntimeSort {
sorter := &RuntimeSort{field: field, objs: objs, origPosition: make([]int, len(objs))}
for ix := range objs {
sorter.origPosition[ix] = ix
}
return sorter
}
func (r *RuntimeSort) Len() int {
@@ -102,6 +137,7 @@ func (r *RuntimeSort) Len() int {
func (r *RuntimeSort) Swap(i, j int) {
r.objs[i], r.objs[j] = r.objs[j], r.objs[i]
r.origPosition[i], r.origPosition[j] = r.origPosition[j], r.origPosition[i]
}
func isLess(i, j reflect.Value) (bool, error) {
@@ -146,3 +182,12 @@ func (r *RuntimeSort) Less(i, j int) bool {
}
return less
}
// Returns the starting (original) position of a particular index. e.g. If OriginalPosition(0) returns 5 than the
// the item currently at position 0 was at position 5 in the original unsorted array.
func (r *RuntimeSort) OriginalPosition(ix int) int {
if ix < 0 || ix > len(r.origPosition) {
return -1
}
return r.origPosition[ix]
}