diff --git a/helper/schema/schema_sort.go b/helper/schema/schema_sort.go index d803250c8..798c740eb 100644 --- a/helper/schema/schema_sort.go +++ b/helper/schema/schema_sort.go @@ -4,6 +4,7 @@ package schema // to a schema. type listSort struct { List []interface{} + Map map[int]int Schema *Schema } @@ -17,4 +18,19 @@ func (s *listSort) Less(i, j int) bool { func (s *listSort) Swap(i, j int) { s.List[i], s.List[j] = s.List[j], s.List[i] + + // Build the mapping. We have to make sure we get to the proper + // place where the final target is, not the current value. + if s.Map == nil { + s.Map = make(map[int]int) + } + i2 := i + j2 := j + if v, ok := s.Map[i]; ok { + i2 = v + } + if v, ok := s.Map[j]; ok { + j2 = v + } + s.Map[i], s.Map[j] = j2, i2 } diff --git a/helper/schema/schema_sort_test.go b/helper/schema/schema_sort_test.go index cccbdf3e1..b46c602c6 100644 --- a/helper/schema/schema_sort_test.go +++ b/helper/schema/schema_sort_test.go @@ -12,7 +12,7 @@ func TestListSort_impl(t *testing.T) { func TestListSort(t *testing.T) { s := &listSort{ - List: []interface{}{5, 2, 1}, + List: []interface{}{5, 2, 1, 3, 4}, Schema: &Schema{ Order: func(a, b interface{}) bool { return a.(int) < b.(int) @@ -22,8 +22,19 @@ func TestListSort(t *testing.T) { sort.Sort(s) - expected := []interface{}{1, 2, 5} + expected := []interface{}{1, 2, 3, 4, 5} if !reflect.DeepEqual(s.List, expected) { t.Fatalf("bad: %#v", s.List) } + + expectedMap := map[int]int{ + 0: 2, + 1: 1, + 2: 3, + 3: 4, + 4: 0, + } + if !reflect.DeepEqual(s.Map, expectedMap) { + t.Fatalf("bad: %#v", s.Map) + } }